Symfony 2 - Call controller from another controller

I would like to use the controller method from another package in my controller.

The this-> forward method needs 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 the service, but I want to know if its the best solution, or if they are different.

+4
source share
2 answers

$this->forward accepts arguments in the following order:

  • The logical name of the controller action in string format, that is, "AcmeHelloBundle: Hello: fancy"
  • Parameters that should be passed as query variables in array format, i.e. array ('name' => $ name, 'color' => 'green',)

, .

+6

, . , .

, :

use AppBundle\Controller\MySourceDataController;

:

$response = MySourceDataController::getTheData( $option1, $option2 );

Request, :

$response = MySourceDataController::getTheData( new Request( array(
    'server' => 'USAServer1',
) ), $option2 );

. $option2, , URL-, :

* @Route("/mydata/{server}/", name="api-source-data")
* @param Request $request
* @param         $server

, JSON , $response:

if ( 0 === strpos( $response->headers->get( 'Content-Type' ), 'application/json' ) ) {
    $response = json_decode( $response->getContent(), true );
}

Voila. .:)

+2

All Articles