问题
Can anyone give me direction on how to accomplish cross controller variable exchange and/or function calls?
I'm new to Symfony and I have a reasonably complex practice sample site which has two controllers - PageController and BlogController.
PageController has actions to generate my home, about and contact page. The home page simply has a list of blogs.
The BlogController has all the CRUD related functions - create, delete etc
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.
In addition, I need to find a solution which will allow the form to submit and the listings to refresh via AJAX.
回答1:
Either using forward method directy
$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
services:
your_service:
class: Acme\DemoBundle\Controller\BlogController
Then you can use
$service = $this->get('your_service');
$service->myFunction();
You could also look into setting up a form factory service (bit more advanced)
UPDATE:
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 ]]
回答2:
Although @Tom Toms answer is correct, I would recommend another approach in order to minimize dependencies:
Just create a route for your Blog function and then use $this->redirectToRoute
in your PageController thereby the action will be simply redirected to the assigned route, so you have no forwarding (although I think that the forwad action will create nothing more then a redirect) or service implementation with injections just a simple redirect
来源:https://stackoverflow.com/questions/27734954/symfony-calling-functions-between-controllers