Redirecting in service - symfony2

前端 未结 5 474
南方客
南方客 2021-01-17 22:03

May I perform redirection to another controller within service?

I have implemented a service based on example provided by @Artamiel.

My function code which i

5条回答
  •  离开以前
    2021-01-17 22:43

    This is possible but I would not recommend it. To redirect from service you should provide proper API for you event for example like in: FOSUserBundle where you are receiving instance of FilterUserResponseEvent and you can set response on that event object:

    class RegistrationListener implements EventSubscriberInterface
    {
        // dependencies
        // ...
    
        public static function getSubscribedEvents()
        {
            return array(
                FOSUserEvents::REGISTRATION_SUCCESS     => 'onSuccess',
            );
        }
    
        public function onSuccess(FilterUserResponseEvent $event)
        {
            $url = $this->router->generate('some_url');
    
            $event->setResponse(new RedirectResponse($url));
        }
    }
    

    This is possible thanks to controller:

    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
    
    if (null === $response = $event->getResponse()) {
        // create response
    }
    // return response from event
    

提交回复
热议问题