Symfony 4 Event Dispatcher-是否有一些解决方案,如何使用Event Dispatcher过滤值? 如wordpress的“ add_filter”功能

问题描述

是否有一些解决方案,如何使用Symfony Event dispatcher(如Sympressy Event dispatcher)来过滤值(如wordpress)以及返回已过滤值的add_filter? 也许将属性存储在事件中并用订阅者进行编辑?

解决方法

您提出的解决方案是我能想到的最好的解决方案。没有像WordPress过滤器或Joomla插件那样对值进行后处理的“本机”机制。

如果调度自定义事件并填充要过滤的对象,则可以轻松添加订阅者以执行您的意思。由于对象总是通过引用传递,因此对该对象的任何更改都将在控制器中传播。

例如

控制器:

$product = $this->productRepository->get($someId);
$this->eventDispacther->dispatch(
    BeforeDisplayEvent::class,new BeforeDisplayEvent($product)
)

return $this->render('product.html.twig',['product' => $product]);

订户:

public function alterProduct(BeforeDisplayEvent $event)
{
    $product->setSomething($this->yourFilter($product));
}