首页 > 解决方案 > Symfony EventSubscriber 使用 KernelEvents 抛出偏移 0 错误

问题描述

所以我正在学习创建 API 的基础。我正在尝试通过使用 API 与创建新用户进行交互,但是我需要使用 symfony 来散列密码。

我制作了一个 PasswordEncoderSubscriber 方法,该方法在将密码插入数据库之前对其进行哈希处理。

private $encoder;

public function __construct(PasswordEncoderInterface $encoder)
{
    $this->encoder = $encoder;
}
public static function getSubscribedEvents()
{
    return [
        KernelEvents::VIEW => ['encodePassword' => EventPriorities::PRE_WRITE]
    ];
}

public function encodePassword(ViewEvent $event)
{
    $result = $event->getControllerResult();
    $method = $event->getRequest()->getMethod();

    if ($result instanceof User && $method === "POST") {
        $hash = $this->encoder->encodePassword($result, $result->getPassword());
        $result->setPassword($hash);
    }
}

KernelEvents::View在将函数encodePassword写入数据库之前,我使用EventPriorities::PRE_WRITE.

这是我得到的错误:注意:未定义的偏移量:0

KernelEvents::VIEW代码在我忘记了什么之后就中断了?

谢谢!

标签: phpsymfony

解决方案


根据symfony 手册,您应该提供处理程序,它的优先级为包含 2 个项目的数组:

return [
    KernelEvents::EXCEPTION => [
        ['processException', 10],
    ],
];

所以,你的代码应该是:

public static function getSubscribedEvents()
{
    return [
        KernelEvents::VIEW => [
            ['encodePassword', EventPriorities::PRE_WRITE],
        ]
    ];
}

推荐阅读