简体   繁体   中英

Symfony 2 - Call controller from another controller

I would like use a method of controller from another bundle, in my controller.

The method this->forward need a Response object, and i don't know how to use it.

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;
}

And i saw that i can use service but i want to know if its the best solution or they are another.

$this->forward takes arguments in this order:

  1. Logical Name of controller action in string format ie 'AcmeHelloBundle:Hello:fancy'
  2. Parameters to be passed as request variables in array format ie 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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM