Search code examples
wordpresssymfonyeventssymfony-eventdispatcher

Symfony 4 Event Dispatcher - is there some solution how to filter value with Event Dispatcher? (like wordpress "add_filter" function)


is there some solution how to filter value/values with Symfony Event Dispatcher like wordpress with add_filter that returns filtered value? Maybe store properties in Event and edit them with subscriber?


Solution

  • The solution you proposed is the best I can think of. There is no "native" mechanism intended to post-process a value like in WordPress filters or Joomla plugins.

    If you dispatch a custom event and populate with the object you want to "filter" you can easily add a subscriber to do what you mean. As objects are always passed by reference, any alteration to the object will be propagated in the controller.

    E.g.

    controller:

    $product = $this->productRepository->get($someId);
    $this->eventDispacther->dispatch(
        BeforeDisplayEvent::class,
        new BeforeDisplayEvent($product)
    )
    
    return $this->render('product.html.twig', ['product' => $product]);
    

    subscriber:

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