在symfony 3中,我订阅了
FOSUserEvents :: REGISTRATION_COMPLETED 用地址数据填写第二个表并写日志。
namespace AppBundle\EventListener;
use AppBundle\Entity\Address;
use Doctrine\ORM\EntityManager;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FilterUserResponseEvent;
class RegistrationSubscriber implements EventSubscriberInterface
{
private $em;
private $container;
public function __construct(EntityManager $em,ContainerInterface $container)
{
$this->em = $em;
$this->container = $container;
}
public static function getSubscribedEvents()
{
return [
FOSUserEvents::REGISTRATION_COMPLETED => [
['onRegistrationCompleted',0]
],
];
}
public function onRegistrationCompleted(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$address = new Address();
$address->addAddress($user);
$this->em->persist($address);
$this->em->flush();
$this->container->get('app.logging')->write('Anmeldung',array('customer'=>$user->getId()));
}
}
services.yml:
app.registration_listener:
class: 'AppBundle\EventListener\RegistrationSubscriber'
arguments: ['@doctrine.orm.entity_manager']
tags:
- { name: kernel.event_subscriber}
app.logging:
class: AppBundle\Util\LogHandler
arguments: ['@doctrine.orm.entity_manager']
public: true
提交注册表后,会触发FOSUserEvents :: REGISTRATION_COMPLETED,但它会运行两次,因为地址数据和日志数据会被写入两次。
可能是什么原因?
答案 0 :(得分:2)
我自己找到了。
在symfony 3.3的services.yml中,我使用了该选项 autoconfigure:true , 所以服务和事件订阅者会自动加载。
这就是事件被触发两次的原因。