php 如何从控制器内部访问不同的控制器 Symfony2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15827384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access a different controller from inside a controller Symfony2
提问by chirag7jain
I need to access a method from a different controller inside another controller. How can I do it? Can I use this->getmethod?
我需要从另一个控制器内的不同控制器访问一个方法。我该怎么做?可以用this->get方法吗?
Can I include the controller inside my current controller and make a object of it and access the method via the object? Is it "ok" to do it this way?
我可以将控制器包含在当前控制器中并为其创建一个对象并通过该对象访问该方法吗?这样做“可以”吗?
I want to call the form method --- newAction of the other controller.
我想调用另一个控制器的表单方法---newAction。
回答by SimonSimCity
If you don't want to define the class as a service, as it doesn't feel as a good practice to me and @Qoop quoted Fabien saying the same, you can use forwarding:
如果您不想将类定义为服务,因为这对我来说不是一个好习惯,@Qoop 引用了Fabien 说同样的话,您可以使用转发:
http://symfony.com/doc/current/controller/forwarding.html
http://symfony.com/doc/current/controller/forwarding.html
public function indexAction($name)
{
$response = $this->forward('AcmeHelloBundle:Hello:fancy', array(
'name' => $name,
'color' => 'green',
));
// ... further modify the response or return it directly
return $response;
}
If you need to embed the output of an internal controller-action in a template, the documentation for Symfonyalso has something for that.
回答by Vitalii Zurian
You can define your controller as service, then get it in another controller.
您可以将控制器定义为服务,然后在另一个控制器中获取它。
In your services.ymldefine needed controller as a service:
在您services.yml定义所需的控制器即服务中:
services:
your_service_name:
class: YourCompany\YourBundle\Controller\YourController
Then in any controller you'll be able to get this service via container:
然后在任何控制器中,您都可以通过容器获得此服务:
$yourController = $this->get('your_service_name');
There is some useful information about Controllers as Servicesin documentation
文档中有一些关于控制器即服务的有用信息

