Redirecting in service - symfony2

前端 未结 5 532
南方客
南方客 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:44

    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(.....);    
        }
    }
    

提交回复
热议问题