问题描述
我试图将我的一项服务注入到EntityListener
中,以便在实体更新时调用某些特定于应用程序的行为.
I am trying to inject one of my services into an EntityListener
in order to call some application specific behaviour when an entity gets updated.
我的Logger
服务,用于将事件存储在数据库的LogEntry
实体中:
My Logger
service, used to store events in a LogEntry
entity in my database:
class Logger
{
/**
* @var EntityManager $manager The doctrine2 manager
*/
protected $manager;
//...
}
听众:
class EntityListener
{
public function __construct(Logger $logger)
{
$this->logger = $logger;
// ...
}
}
以及我的service.yml
中的服务定义:
And the service definitions in my service.yml
:
listener:
class: Namespace\EntityListener
arguments: [@logger]
tags:
- { name: doctrine.event_listener, event: preUpdate }
logger:
class: Namespace\Logger
arguments: [@doctrine.orm.entity_manager]
不幸的是,它导致ServiceCircularReferenceException
:
问题显然是我将doctrine
注入了我的服务,同时它也被自动注入了我的监听器.我该如何进行?我发现非常相似的问题但是可以接受的答案是注入容器,这显然是不利的.
The problem obviously is that I inject the doctrine
into the my service while it is also automatically injected into my listener. How do I proceed? I found a very similar question but the accepted answer is to inject the container which is obviously not favourable.
任何有关如何解决我的问题的建议将不胜感激.
Any suggestions on how to solve my issue would be appreciated.
小注释:我想避免依赖惰性服务的解决方案(如果可能).
Small side note: I would like to avoid a solution depending on lazy services if possible.
推荐答案
首先,我从EventListener
切换为EventSubscriber
.从文档:
First of all I switched from an EventListener
to an EventSubscriber
. From the docs:
事实证明,可以像这样通过传递的$args
参数访问ObjectManager
:
It turns out one can access the ObjectManager
via the passed $args
-parameter like so:
/** @var Doctrine\Common\Persistence\ObjectManager $manager */
$manager = $args->getObjectManager();
因此可以直接在回调中使用它:
So either use it directly in the callback:
public function postUpdate(LifecycleEventArgs $args)
{
$manager = $args->getObjectManager();
// ...
...或将其设置为对象字段:
...or set it to an object field:
/** @var ObjectManager $manager */
private $manager;
public function postUpdate(LifecycleEventArgs $args)
{
$this->manager = $args->getObjectManager();
// ...
这篇关于将EntityManager依赖服务注入侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!