2014-02-18 179 views
0

调用函数我有两个控制器从另一个控制器

DefaultController

class DefaultController extends Controller 
{ 
    public function indexAction() 
    { 

ApiController

class ApiController extends Controller 
{ 
    public function getCategoryAction() 
    { 

现在我想从我的DefaultController调用getCategoryAction。

这是不可能的,或者我该怎么做?

+0

你是什么意思的“调用”getCategoryAction。你是否想要返回相同的响应/模板或之后处理返回的数据? – nifr

+0

getCategoryAction显示categoryList.xml(因为此控制器用于API使用)。所以,我想在indexAction() – whitebear

+0

中使用categoryList.xml,你可以更具体地说明你的意思是“使用它”吗?你想对它做些什么(比如阅读和改变内容)或者只是返回与API操作相同的XML? – nifr

回答

0

可以配置控制器作为一个服务,然后使用

$this->forward('controller.service.name')->methodOnTheController() 
1

称他们有forwarding中的Symfony2 。所以,你可以做某事这样的:

class DefaultController extends Controller 
{ 
    public function indexAction() 
    { 
     // @var Response $categoryListResponse 
     $categoryListResponse = $this->forward('YourBundle:Api:getCategory'); 
     // ... further modify the response or return it directly 
     return $categoryListResponse; 
    } 
} 

哪里$categoryListResponseResponse类型,代表一个HTTP响应。所以你可以从这个回应中得到$categoryListResponse->getContent()

0

可以扩展ApController控制器是这样的:

class ApiController extends DefaultController 
{ 
    public function yourAction() 
    { 
     $this->getCategoryAction(); 
    } 
} 

甚至更​​好创建一个MyClass的类(如果getCategoryAction将被重复使用)注册为服务

这一切都取决于你想要什么实现在最后