Symfony2如何在不硬编码路由名称的情况下重定向到操作?

标签 symfony

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

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

但是newAction实际上是在子类中调用UserController,所以我无法指定路由名称$route 在我的 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

最佳答案

您可以使用面向对象的整个概念,并在您的抽象类中拥有一个名为getRouteName()的接口(interface)方法:

abstract public function getRoute();

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

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

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

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

也许可以尝试一下,然后让我们知道是否可行。

关于Symfony2如何在不硬编码路由名称的情况下重定向到操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9719686/

相关文章:

Symfony2 - 从编译器 channel 访问内核

php - Symfony2 语言选择器

php - JMS 序列化程序覆盖 FOSRestBundle 中的组

php - 使用 Doctrine 在 Symfony2 中进行非常低效的 DQL 查询。需要改进

php - 如何使用空字符串值将实体保存在数据库中

php - 如何重建 Symfony Encore Assets ?

symfony 路由注解需求约束

php - 尝试运行向下/回滚命令时找不到 Doctrine Migration 类错误

php - 如何从特定主题获取当前id?

symfony - 动态 Twig 变量名称