控制器之间的Symfony调用功能 [英] Symfony calling functions between controllers
问题描述
有人可以指导我如何完成跨控制器变量交换和/或函数调用吗?
Can anyone give me direction on how to accomplish cross controller variable exchange and/or function calls?
我是Symfony的新手,我有一个相当复杂的练习示例站点,该站点具有两个控制器-PageController和BlogController.
I'm new to Symfony and I have a reasonably complex practice sample site which has two controllers - PageController and BlogController.
PageController可以执行一些操作来生成我的主页,关于和联系页面.主页仅包含博客列表.
PageController has actions to generate my home, about and contact page. The home page simply has a list of blogs.
BlogController具有与CRUD相关的所有功能-创建,删除等
The BlogController has all the CRUD related functions - create, delete etc
我的问题是我想从PageController调用我的BlogController:createAction函数,这样我就可以在主页上博客列表上方显示一个博客创建表单,或者只传递包含新博客表单数据的变量.
My issue is that I want to call my BlogController:createAction function from the PageController so I can present a blog create form above the blog listings on the homepage OR just pass the variable containing the new blog form data.
此外,我需要找到一种解决方案,以允许表单提交并通过AJAX刷新列表.
In addition, I need to find a solution which will allow the form to submit and the listings to refresh via AJAX.
推荐答案
直接使用向前方法
$response = $this->forward('AcmeDemoBundle:Blog:myFunction', array(
'name' => $name,
));
http://symfony.com/doc/current/book/controller.html#forwarding-to-another-controller
或者,您也可以将博客控制器定义为服务.
Or alternatively, you could define the blog controller as a service.
service.yml
service.yml
services:
your_service:
class: Acme\DemoBundle\Controller\BlogController
然后您就可以使用
$service = $this->get('your_service');
$service->myFunction();
您还可以考虑设置表格工厂服务(高级一点)
You could also look into setting up a form factory service (bit more advanced)
更新:
在您发布帖子之后,我实施了一项服务,但出现以下错误:
Following your post I implemented the a service but got the following error:
Error: Call to a member function get() on a non-object
当我在服务声明中添加以下行时,此问题已解决:
This got fixed when I added the following line to the service declaration:
calls:
- [ setContainer, [ @service_container ]]
这篇关于控制器之间的Symfony调用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!