6

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.

2 Answers 2

8

$this->forward takes arguments in this order:

  1. Logical Name of controller action in string format i.e. 'AcmeHelloBundle:Hello:fancy'
  2. 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.

Sign up to request clarification or add additional context in comments.

Comments

2

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. :)

1 Comment

Is it clean? That feels both natural and hacky to me. I'm a symfony beginner and I have no idea if I should/could use that in production.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.