服务中的重定向 - symfony2 [英] Redirecting in service - symfony2
问题描述
我可以重定向到服务中的另一个控制器吗?
May I perform redirection to another controller within service?
我已经根据 @提供的示例实现了一项服务阿塔米尔.
我的由控制器执行的函数代码如下所示:
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'));
}
我已经检查过,!$session->get("App_Books_Chosen_Lp")
是真的.尽管如此,我并没有被重定向到 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.
推荐答案
我不知道您是如何定义服务的,但下面的示例工作正常.假设您从控制器调用服务.
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
服务类
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'));
}
}
控制器
public function createAction(Request $request)
{
//.........
return $this->userService->create();
}
更新
尽管上面的原始答案回答了原始问题,但这不是最佳做法,因此如果您想要更好的方法,请执行以下操作.首先不要将@router
注入服务中,做如下修改.
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(.....);
}
}
这篇关于服务中的重定向 - symfony2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!