php - 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
代码在我忘记了什么之后就中断了?
谢谢!
解决方案
根据symfony 手册,您应该提供处理程序,它的优先级为包含 2 个项目的数组:
return [
KernelEvents::EXCEPTION => [
['processException', 10],
],
];
所以,你的代码应该是:
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => [
['encodePassword', EventPriorities::PRE_WRITE],
]
];
}
推荐阅读
- python - Numpy:np.repeat 和 np.broadcast_to 之间的区别
- javascript - React 钩子状态对于几个相等的事件有不同的值
- mapbox-gl-js - 簇几何与原始几何不同(有偏移,但为什么?)
- directus - 我无法更新输入值 Directus
- c++ - C++ 原始指针和“删除”
- esxi - ESXI 合并两个服务器来共享它们的资源?
- react-native - 使用 Wix React Native Navigation 关闭模式并更改选项卡
- machine-learning - 机器学习项目——我的目标变量在时间上分布不均匀
- java - 由于违反约束,节点 setProperty 在 Magnolia CMS 中给出了 RepositoryException
- django - Django:如何过滤具有多对多关系的数据