无法自动连线服务 [英] Cannot autowire service
问题描述
我正在尝试从FOSUserBundle(Symfony3.4)实现UserManager.
I am trying to implement UserManager from FOSUserBundle (Symfony3.4).
Service/Register.php
Service/Register.php
<?php
namespace AppBundle\Service;
use FOS\UserBundle\Model\UserManager;
class Register
{
private $userManager;
public function __construct(UserManager $userManager)
{
$this->userManager = $userManager;
}
public function register() {
$user = $this->userManager->findUserByUsernameOrEmail('aaa@gmail.clom');
if($user){
return false;
}
return true;
}
}
当我尝试调用此方法时,我得到:
When I try call this method I get:
无法自动装配服务"AppBundle \ Service \ Register":方法"__construct()"的参数"$ userManager"引用类"FOS \ UserBundle \ Model \ UserManager",但不存在此类服务.您也许应该将此类作为现有"fos_user.user_manager.default"服务的别名.
Cannot autowire service "AppBundle\Service\Register": argument "$userManager" of method "__construct()" references class "FOS\UserBundle\Model\UserManager" but no such service exists. You should maybe alias this class to the existing "fos_user.user_manager.default" service.
我现在该怎么办?
推荐答案
我在使用其他服务时遇到了类似的问题(在Symfony 4中,但原理应适用于3.4),并设法在Symfony文档页面上找到了答案. 自动定义服务依赖项(自动装配)
I had a similar problem (in Symfony 4, but the principles should apply to 3.4) with a different service and managed to find the answer on the Symfony doc page Defining Services Dependencies Automatically (Autowiring).
以下是该页面的摘录:
配置自动装配的主要方法是创建一个ID与其类完全匹配的服务.在上一个示例中,该服务的ID为
AppBundle\Util\Rot13Transformer
,这使我们能够自动为该类型自动接线.
The main way to configure autowiring is to create a service whose id exactly matches its class. In the previous example, the service's id is
AppBundle\Util\Rot13Transformer
, which allows us to autowire this type automatically.
这也可以使用别名来实现.
This can also be accomplished using an alias.
您需要一个别名,因为服务ID与类名不匹配.这样做吧:
You need an alias because the service ID doesn't match the classname. So do this:
# app/config/services.yml
services:
# ...
# the `fos_user.user_manager.default` service will be injected when
# a `FOS\UserBundle\Model\UserManager` type-hint is detected
FOS\UserBundle\Model\UserManager: '@fos_user.user_manager.default'
这篇关于无法自动连线服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!