Symfony2 如何在没有硬编码路由名称的情况下重定向到操作? [英] Symfony2 how to redirect to an action without hardcoding route name?

查看:27
本文介绍了Symfony2 如何在没有硬编码路由名称的情况下重定向到操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象 CRUDController 扩展Controller.在我的 newAction 中,操作系统成功,我想使用 redirect 方法重定向到 showAction($slug):

I've an abstract CRUDController extending Controller. In my newAction, os success, i'd like to redirect to showAction($slug) using redirect method:

return $this->redirect($this->generateUrl($route, $params));

但是newAction实际上是在子类中调用 UserController,所以我不能指定路由名称$route 在我的 CRUDController 中.

But newAction is actually called in the subclass UserController, so i can't specify route name $route in my CRUDController.

class UserController extends CRUDController { }

abstract class CRUDController extends Controller
{
    /** @Template */
    public function showAction($slug) { }

    /** @Template */
    public function newAction(Request $request)
    {

        $model = $this->createModel();
        $form  = $this->createForm($this->createType(), $model);

        if('GET' == $request->getMethod())
            return array('form' => $form->createView());

        $form->bindRequest($request);

        if(!$form->isValid()) return array(
            'errors' => $this->get('validator')->validate($model),
            'form'   => $form->createView()
        );

        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($model);
        $em->flush();

        // Success, redirect to showAction($slug)
    }

}

路线示例:

users_show:
  pattern: /users/show/{slug}
  defaults: { _controller: AcmeSecurityBundle:User:show }
  requirements:
    _method:  GET

users_new:
  pattern: /users/new
  defaults: { _controller: AcmeSecurityBundle:User:new }
  requirements:
    _method:  GET

users_create:
  pattern: /users/new
  defaults: { _controller: AcmeSecurityBundle:User:new }
  requirements:
    _method:  POST

推荐答案

您可以使用 OO 的整个概念,并在您的 抽象 中有一个名为 getRouteName() 的接口方法强>类:

You can work with the whole concept of OO and have an interface method called getRouteName() in your abstract class:

abstract public function getRoute();

然后,在您的具体类或子类 UserController 上,您只需覆盖并实现它:

And then, on your concrete class, or subclass, UserController, you just override and implement that:

public function getRoute()
{
    return 'whatever:Route:YouWant';
}

因此,当在您的抽象类上调用实际的接口方法时,OO 将像魔术一样处理所有事情:

So when, on your abstract class, call the actual interface method, the OO will handle everything like magic:

public function newAction(Request $request)
{
    ...
    return $this->redirect($this->generateUrl($this->getRouteName(), $params));
}

也许尝试一下,让我们知道是否正确.

Maybe try that and let us know if does the job right.

这篇关于Symfony2 如何在没有硬编码路由名称的情况下重定向到操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆