在一个Eventlister中,我想获得security.encoder_factory
。监听器UserManager
确实知道容器,因此$this->get('security.encoder_factor')
显然无法工作。如何在此侦听器中获取security.encoder_factory
属性?
服务:
services:
my.listener:
class: Bla\OrmBundle\EventListener\UserManager
tags:
- { name: doctrine.event_listener, event: prePersist }
的UserManager:
class UserManager {
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof User) {
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($entity);
$password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
$entity->setPassword($password);
}
}
}
答案 0 :(得分:3)
你可以将容器注入其中(但这通常不是一个好习惯,所以尽可能避免使用它):
类别:
class UserManager {
protected $container;
public function __construct(\Symfony\Component\DependencyInjection\ContainerInterface $container) {
$this->container = $container;
}
protected function getEncoderFactory()
{
return $this->container->get('security.encoder_factory');
}
}
服务定义:
services:
my.listener:
class: Bla\OrmBundle\EventListener\UserManager
arguments: [@service_container]
tags:
- { name: doctrine.event_listener, event: prePersist }
同样,这不是一个好主意!如果您不需要,请不要让您的服务容器知道!相反,你可以注入编码器工厂!
类别:
class UserManager {
protected $encoderFactory;
public function __construct(\Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface $encoderFactory) {
$this->encoderFactory = $encoderFactory;
}
}
配置:
services:
my.listener:
class: Bla\OrmBundle\EventListener\UserManager
arguments: [@security.encoder_factory]
tags:
- { name: doctrine.event_listener, event: prePersist }