【问题标题】:Symfony2 why does forward nest request objects?Symfony2 为什么转发嵌套请求对象?
【发布时间】:2013-02-28 09:53:31
【问题描述】:

当我在控制器中执行 forward() 时,我丢失了路由和 route_parameters。

当我有 ParentAction 时,它会转发给 ChildAction。在 Childaction 我做return $this->render('myTemplate.html.twig', array()); 然后请求属性被嵌套!

所以当模板被渲染时,我得到的是$request['attributes']['_route_parameters'],而不是$request['attributes']['request']['attributes']['_route_parameters']

虽然在 ChildAction 中,当我执行$this->getRequest(); 时,层次结构是正常的。

这是一个错误,还是我做错了什么?

【问题讨论】:

    标签: symfony httpresponse forwarding


    【解决方案1】:

    原因是 symfony 不假设你有相同的路由参数。 所以转发的时候需要重新提供新路由需要的路由参数,即使是一样的。

    (顺便说一句,您还必须为新路由提供任何查询参数。)

    public function indexAction($param)
    {
    
        return $this->forward(
            'AppBundle\\Controller\\DefaultController::otherAction',
            array("someOtherParam" => $param),
            $request->query->all() // Causes query string params to be copied
        );
    }
    
    // This route has a different parameter.
    public function otherAction($someOtherParam) ...
    

    【讨论】:

      【解决方案2】:

      一个可能的解决方案是在转发时将您的请求作为第二个参数传递。

      $response = $this->forward('MyBundle:MyController:myAction', array('request' => $request));
      

      此外,由于 forward 只是 Symfony2 核心功能的快捷方式,this 可能会有所帮助。

      【讨论】:

      • 你能检查我的编辑吗?我可以阅读请求等,但发生了一些奇怪的事情。
      【解决方案3】:

      在我的例子中,以下代码有所帮助:

      $subRequest = $this->container->get('request')->duplicate(
          array(), 
          null, 
          array('topicId' => $topicId,'_controller' => 'SomeBundle:Topic:close'));
      
      return $this->container->get('http_kernel')
          ->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
      

      “Topic”是TopicController,“close”是closeAction

      【讨论】:

        猜你喜欢
        • 2021-01-16
        • 2017-05-19
        • 2021-11-16
        • 1970-01-01
        • 2018-02-01
        • 2020-06-19
        • 1970-01-01
        • 2019-10-27
        • 2014-03-31
        相关资源
        最近更新 更多