Symfony 2 - Call controller from another controller
$this->forward
takes arguments in this order:
- Logical Name of controller action in string format i.e. 'AcmeHelloBundle:Hello:fancy'
- Parameters to be passed as request variables in array format i.e. array('name' => $name,'color' => 'green',)
These parameters can be accessed in the controller using request access functions.
Sometimes you want to bypass security completely and run a command in another controller despite a user's permissions level. Luckily you can do that fairly easily.
First, run a use Command for your controller at the top of the controller you want to use the data from:
use AppBundle\Controller\MySourceDataController;
Then call that function from within your destination controller:
$response = MySourceDataController::getTheData( $option1, $option2 );
If you need to pass a Request object, you can do it this way:
$response = MySourceDataController::getTheData( new Request( array( 'server' => 'USAServer1',) ), $option2 );
This returns a Request with the set parameter of server. I also defined a $option2, this would be a variable often defined in the URL such as:
* @Route("/mydata/{server}/", name="api-source-data")* @param Request $request* @param $server
Lastly, if you're passing JSON in that controller and want to convert it back to an object, you can run this bit of code on the $response:
if ( 0 === strpos( $response->headers->get( 'Content-Type' ), 'application/json' ) ) { $response = json_decode( $response->getContent(), true );}
Voila. Access any controller form any other controller and bypass security notation for the source controller. :)