我正在使用symfony2.8。 我想从另一个控制器跳到控制器。怎么可能?
这是我的源代码
DefaultController.php
class DefaultController extends Controller
public function myFirstAction(){
// do something
if ($a = 1){
$this->mySecondAction() // error
}
else {
return $this->render('AcmeMemberBundle:Default:myFirst.html.twig',array());
}
}
public function mySecondAction(){
//do something
return $this->render('AcmeMemberBundle:Default:mySecond.html.twig',array());
}
$ this-> mySecondAction()显示错误,如
Catchable Fatal Error: Argument 1 passed to Acme\MemberBundle\Controller\DefaultController::secondAction() must be an instance of Symfony\Component\HttpFoundation\Request, none given, called in
答案 0 :(得分:2)
所有Symfony操作都传递一个Request实例。您应该能够通过向两个动作函数添加相应的参数并在调用mySecondAction()时将其传递来修复此错误
此外,不要忘记操作必须返回响应,您不会在代码中返回mySecondAction()的结果。
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
public function myFirstAction(Request $request){
// do something
if ($a = 1){
return $this->mySecondAction($request) // Note the return I added here
}
else {
return $this->render('AcmeMemberBundle:Default:myFirst.html.twig',array());
}
}
public function mySecondAction(Request $request){
//do something
return $this->render('AcmeMemberBundle:Default:mySecond.html.twig',array());
}
答案 1 :(得分:1)
如果您想跳转到另一个控制器,您可以将其定义为服务,但是如果您在同一个控制器中拥有这些功能,则可以使用@AmericanUmlaut answer。
将控制器定义为服务并获取函数'mySecondAction()'并使用先前定义的服务,例如:
然后您可以将其定义为服务,如下所示: services.yml文件
services:
app.mySecondAction:
class: AppBundle\Controller\DefaultController
calls:
- [setContainer, ["@service_container"]]
控制器:
public function myFirstAction() {
// do something
if ($a = 1) {
//using the service previously defined
$service = $this->get('app.mySecondAction');
return $service->mySecondAction();
} else {
return $this->render('AcmeMemberBundle:Default:myFirst.html.twig', array());
}
}
public function mySecondAction(){
//do something
return $this->render('AcmeMemberBundle:Default:mySecond.html.twig',array());
}