Symfony2:在新控制器中使用 renderView 方法

Symfony2: Using renderView method in new Controller

我有两个控制器:

class FirstController extends Controller
{
    /**
     * @Route("/first")
     */
    public function indexAction()
    {
        $second = new SecondController();
        $second->doit();
    }
}


class SecondController extends Controller
{
    public function doit()
    {
        $render = $this->renderView('::base.html.twig');
        //write $render to disk
    }
}

而不是 'done' 被写入我的屏幕,我得到了错误:

我做错了什么?

您不应该自己实例化控制器。该框架应该为您做到这一点。如果您在 controller1 中,并希望 controller2 实际处理请求,您可以使用一些解释,您需要 forward to it,像这样:$this->forward('MyBundle:MyController:myaction)

此外,您也许应该在服务中使用 doit 方法。控制器应该保持苗条,只关心 HTTP:

  • 他们收到请求
  • 他们根据请求调用服务,该服务应该对 HTTP 一无所知,并且可以从命令和控制器调用
  • 他们 return 根据服务回答的内容做出响应。