【发布时间】:2018-07-08 18:28:26
【问题描述】:
尝试注册一个 Doctrine EventSubscriber,但实际上没有触发任何事情。
我已经在相关实体上设置了@ORM\HasLifeCycleCallbacks 注释。
这里是订阅者:
<?php
namespace App\Subscriber;
use App\Entity\User;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserPasswordChangedSubscriber implements EventSubscriber
{
private $passwordEncoder;
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public function getSubscribedEvents()
{
return [Events::prePersist, Events::preUpdate, Events::postLoad];
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof User) {
return null;
}
$this->updateUserPassword($entity);
}
public function preUpdate(PreUpdateEventArgs $event)
{
$entity = $event->getEntity();
if (!$entity instanceof User) {
return null;
}
$this->updateUserPassword($entity);
}
private function updateUserPassword(User $user)
{
$plainPassword = $user->getPlainPassword();
if (!empty($plainPassword)) {
$encodedPassword = $this->passwordEncoder->encodePassword($user, $plainPassword);
$user->setPassword($encodedPassword);
$user->eraseCredentials();
}
}
}
让这特别令人沮丧的部分是,在 Symfony 3 中,当自动装配被关闭并且我手动编码我的所有服务时,相同的代码和配置很好。
但是,现在,即使我以通常的方式为此手动编写服务条目,仍然没有任何反应。
编辑:
在尝试了 Symfony 文档中建议的 Domagoj 之后,这是我的 services.yaml:
App\Subscriber\UserPasswordChangedSubscriber:
tags:
- { name: doctrine.event_subscriber, connection: default }
没有用。有趣的是,如果我不实现 EventSubscriber 接口,Symfony 会抛出异常(正确)。然而我在代码中的断点被完全忽略了。
我考虑过 EntityListener,但它不能有带参数的构造函数,不能访问容器,我不应该这样做;这应该工作:/
【问题讨论】:
-
请显示所有相关的配置文件。你说了一些关于自动装配和一些关于“手动”配置的东西,但你没有在这里报告相关代码......
-
目前没有可发布的配置,这是相关的,因为没有任何配置。下面的答案提出了一个我即将尝试的建议(涉及配置)。在自动装配方面,Symfony 3.3 带来了一些关于自动将对象注入类而无需配置(或可选配置)的新变化。现在我要使用默认配置。你可以在这里阅读更多内容symfony.com/doc/current/service_container/3.3-di-changes.html
标签: symfony events doctrine subscriber