How to add middleware for one or two controllers in Symfony4?
Asked Answered
I

1

5

I want a few controllers which have methods like this:

public function syncAction(EntityManager $em)
{
    $posts = $em->getRepository('App:Posts')->findAllByOwner($this->getUser());

    return new JsonResponse(['ok' => true, 'posts' => $this->toJson($posts)]);
}

I want to add something like middleware to be automatically jsonify response from all actions of this controller. And be ablw to simple do this:

    return new JsonResponse(['ok' => true, 'posts' => $posts]);

PS Also automatically serialize my instances.

Imperforate answered 22/1, 2018 at 8:16 Comment(0)
O
10

Symfony has no middleware concept, but event listener and subscriber (basically the same thing).

Have a look at https://symfony.com/doc/current/event_dispatcher/before_after_filters.html

You will use kernel.response (KernelEvents::RESPONSE) event, to manipulate the controller response.

Odette answered 22/1, 2018 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.