Php 在自定义类上调用服务会在Symfony中返回可捕获的致命错误
我已经在symfony2中创建了一个新服务,并将“security.context”作为参数。 但是,当我对自定义类或不是控制器的类调用服务时,它总是返回一个缺少参数的错误。我可以知道这个密码有什么问题吗 这是我的服务Php 在自定义类上调用服务会在Symfony中返回可捕获的致命错误,php,symfony,Php,Symfony,我已经在symfony2中创建了一个新服务,并将“security.context”作为参数。 但是,当我对自定义类或不是控制器的类调用服务时,它总是返回一个缺少参数的错误。我可以知道这个密码有什么问题吗 这是我的服务 appbundle.common.services.loggeduserservice: class: Makubex\Pim\AppBundle\Common\Services\LoggedUserService arguments: ["@security.c
appbundle.common.services.loggeduserservice:
class: Makubex\Pim\AppBundle\Common\Services\LoggedUserService
arguments: ["@security.context"]
这是我的服务课
use Symfony\Component\Security\Core\SecurityContext;
class LoggedUserService{
private $context;
public function __construct(AppContext $context)
{
$this->context = $context;
}
public function getCurrentUser()
{
return $this->context;
}
}
我的自定义类
class makubex{
public function getUser(){
$user = new LoggedUserService();
echo $user->getId();
}
}
这里几乎没有什么不对的地方:
security.context
,而是AppContext
对于您正在注入的内容,不是有效的类型提示。您可能希望注入安全性.token\u存储
服务,然后您的类型提示将是TokenStorageInterface
new
关键字(例如newloggeduserservice()
)来实例化类。相反,您应该在ContainerInterface
实例上调用get
方法(例如$user=$this->container->get('appbundle.common.services.loggeduserservice')
)。要做到这一点,您需要访问自定义类(makubex
)中的容器,所以您还必须将其注入appbundle.common.services.loggeduserservice:
class: Makubex\Pim\AppBundle\Common\Services\LoggedUserService
arguments: ["@security.token_storage"]
服务类别:
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface
class LoggedUserService{
private $context;
public function __construct(TokenStorageInterface $context)
{
$this->context = $context;
}
public function getCurrentUser()
{
return $this->context;
}
}
你们班:
class makubex{
public function __construct($container) {
$this->container = $container;
//you need to inject container or just inject only instance of your LoggedUserService not whole container since this is considered as a bad practice
}
public function getUser(){
$user = $this->container->get('appbundle.common.services.loggeduserservice');
echo $user->getId();
}
}
我忘了,这是确切的错误信息。可捕获的致命错误:传递给Makubex\Pim\AppBundle\Common\Services\LoggedUserService::\uu construct()的参数1必须是Makubex\InfrastructureBundle\Application\AppContext的实例,未给出任何实例,在第28行的C:\wamp\www\pim\src\Makubex\pim\AppBundle\Backoffice\CommandProcessors\saveCustomAttributeCommand.php中调用,并在第19行的C:\wamp\www\pim\src\Makubex\pim\AppBundle\Common\Services\LoggedUserService.php中定义(500内部服务器错误)