我想将当前用户注入实体监听器,但我遇到了ServiceCircularReferenceException
。
我知道还有其他问题需要处理这个问题,一个提到的解决方案是将整个service_container注入到监听程序中,但这不起作用。
然后我偶然发现了a seemingly duplicate question,其中提供的接受答案是实现UserCallable。但这再次产生了完全相同的例外。
可能是因为我对FOSUserBUndle的依赖吗?
我该如何解决这个问题?
例外:
[Symfony的\元器件\ DependencyInjection \异常\ ServiceCircularReferenceException] 检测到服务的循环引用 “doctrine.orm.default_entity_manager”,路径: “doctrine.orm.default_entity_manager - > doctrine.dbal.default_connection - > h nassetdb.approval_listener - > security.context - > security.authentication.manager - > fos_user.user_provider.username - > fos_user.user_manager”。
我的UserBundle service.yml条目:
parameters:
hn_user_callable.class: Hn\UserBundle\Services\UserCallable
hn_user.callable:
class: %hn_user_callable.class%
arguments: ["@service_container"]
我如何设置我的实体监听器:
hnassetdb.approval_listener:
class: %approval_listener.class%
arguments: ['@hn_user.callable', '@logger']
tags:
- { name: doctrine.event_listener, event: onFlush }
UserCallable:
<?php
namespace Hn\UserBundle\Services;
use Hn\UserBundle\Entity\User;
use Hn\UserBundle\Exception\NoCurrentUserAvailableException;
use Symfony\Component\DependencyInjection\ContainerInterface;
class UserCallable implements UserCallableInterface
{
/**
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* @return User
* @throws \Hn\UserBundle\Exception\NoCurrentUserAvailableException
*/
public function getCurrentUser()
{
$currentUser = $this->container->get('security.context')->getToken()->getUser();
if (!$currentUser instanceof User) {
throw new NoCurrentUserAvailableException();
}
return $currentUser;
}
}
我的听众的相关部分:
class ApprovalListener extends ContainerAware implements EventSubscriber {
/**
* @var \Hn\UserBundle\Entity\User
*/
protected $currentUser;
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
public function __construct(UserCallableInterface $userCallable, LoggerInterface $logger)
{
$this->currentUser = $userCallable->getCurrentUser();
$this->logger = $logger;
}
...
}