FriendsOfSymfony / FOSRestBundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony
http://symfony.com/doc/master/bundles/FOSRestBundle/index.html
MIT License
2.79k stars 704 forks source link

add event to initialize view context globally #2262

Open pichelour opened 4 years ago

pichelour commented 4 years ago

Hello,

In our API, we must always initialize the same view context, based on a service.

I must add this in every controller:

        $view = $this->view($data, $status);
        $context = new Context();
        $context->setGroups($this->groupsResolver->getGroups());
        $view->setContext($context);

        return $this->handleView($view);

I made a trait to not duplicate code, it works but I feel it can be better.

I thought of adding an event in ViewHandler->handle, a listener can then do the job of setting the view context.

    public function handle(View $view, Request $request = null)
    {
        if (null === $request) {
            $request = $this->requestStack->getCurrentRequest();
        }

+       $this->eventDispatcher->dispatch(new HandleViewEvent($view, $request));

What do you think of it?

Thanks!