我有一个事件监听器注册如下:
evo_app.listener:
class: %evo_app.listener.class%
arguments: [@service_container, @event_dispatcher]
tags:
- { name: doctrine.event_listener, event: prePersist }
- { name: doctrine.event_listener, event: postPersist }
- { name: doctrine.event_listener, event: preUpdate }
和服务:
<?php
namespace Evo\AppBundle\Listener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Evo\BackendBundle\Entity\Contact;
use Evo\UserBundle\Entity\Customer;
use Evo\UserBundle\EvoUserEvents;
use Evo\UserBundle\Event\CustomerEvent;
class Listener
{
/**
*
* @var \Symfony\Component\DependencyInjection\Container
*/
protected $container;
/**
*
* @var \Symfony\Component\EventDispatcher\EventDispatcher
*/
protected $eventDispatcher;
/**
* constructor
*
* @param Container $container
* @param EventDispatcher $eventDispatcher
*/
public function __construct(Container $container, EventDispatcher $eventDispatcher)
{
$this->container = $container;
$this->eventDispatcher = $eventDispatcher;
}
/**
* prePersist
*
* @param LifecycleEventArgs $args
*/
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$em = $args->getEntityManager();
// Contact entity
if ($entity instanceof Contact) {
if (null === $entity->getType()) {
$entity->setType($em->getRepository('EvoBackendBundle:ContactType')->find(2));
}
}
// Customer entity
if ($entity instanceof Customer) {
$request = $this->container->get('request');
$routeName = $request->getRequestUri();
// On appel l'event d'insert du customer
$this->eventDispatcher->dispatch(EvoUserEvents::PRE_CUSTOMER_INSERTED, $event = new CustomerEvent($entity, $routeName));
}
}
/**
* postPersist
*
* @param LifecycleEventArgs $args
*/
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
// Customer entity
if ($entity instanceof Customer) {
$request = $this->container->get('request');
$routeName = $request->getRequestUri();
// On appel l'event d'insert du customer
$this->eventDispatcher->dispatch(EvoUserEvents::POST_CUSTOMER_INSERTED, $event = new CustomerEvent($entity, $routeName));
}
}
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
// Customer entity
if ($entity instanceof Customer) {
$request = $this->container->get('request');
$routeName = $request->getRequestUri();
// On appel l'event d'insert du customer
$this->eventDispatcher->dispatch(EvoUserEvents::PRE_CUSTOMER_UPDATED, $event = new CustomerEvent($entity, $routeName, $args));
}
}
}
浏览网站时,一切正常。但是当我尝试加载灯具时,特别是“客户”灯具,它创建并持久保存新的客户实体,我在CLI中收到以下错误:
[Symfony的\元器件\ DependencyInjection \异常\ InactiveScopeException] 您无法创建非活动范围(“请求”)的服务(“请求”)。
我想这是因为服务的第58行:$request = $this->container->get('request');
因为CLI模式无法访问请求。
如何使此服务适用于浏览器和CLI?