Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting in service - symfony2

Tags:

symfony

May I perform redirection to another controller within service?

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

My function code which is executed by controller looks like this:

 public function verifyanddispatch() {
        $session = $this->request->getSession();
        if(!$session->get("App_Books_Chosen_Lp")) return new RedirectResponse($this->router->generate('app_listbooks'));
    }

I have checked and !$session->get("App_Books_Chosen_Lp") is true. Nonetheless I am not redirected to app_listbooks controller.

I think that this is because I return redirect response not directly in controller rather than in a service.

like image 269
Abdel5 Avatar asked Jun 28 '15 19:06

Abdel5


2 Answers

I don't know how you defined your service but example below works fine. Assuming that you're calling service from your controller.

services.yml

services:
    application_backend.service.user:
        class: Application\BackendBundle\Service\UserService
        arguments:
            - @router

Service class

namespace Application\BackendBundle\Service;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;

class UserService
{
    private $router;

    public function __construct(
        RouterInterface $router
    ) {
        $this->router = $router;
    }

    public function create()
    {
        $user = new User();
        $user->setUsername('hello');
        $this->entityManager->persist($user);
        $this->entityManager->flush();

        return new RedirectResponse($this->router->generate('application_frontend_default_index'));
    }
}

Controller

public function createAction(Request $request)
{
    //.........

    return $this->userService->create();
}

UPDATE


Although original answer above answers original question, it is not the best practise so do the following if you want a better way. First of all do not inject @router into service and do the following changes.

// Service
public function create()
{
    .....
    $user = new User();
    $user->setUsername('hello');
    $this->entityManager->persist($user);
    $this->entityManager->flush();
    .....
}

// Controller
public function createAction(Request $request)
{
    try {
        $this->userService->create();

        return new RedirectResponse($this->router->generate(........);
    } catch (......) {
        throw new BadRequestHttpException(.....);    
    }
}
like image 194
BentCoder Avatar answered Nov 03 '22 00:11

BentCoder


From an architecture point of view one should not create a RedirectResponse in a service. One way could be to throw an exception in the service, which is caught in the controller's action where you can easily create a RedirectResponse.

An example can be found here: Redirect from a Service in Symfony2

like image 28
Moritz Avatar answered Nov 03 '22 00:11

Moritz