How to Forward Requests to another Controller

How to Forward Requests to another Controller

Though not very common, you can also forward to another controller internally with the forward() method provided by the Symfony\Bundle\FrameworkBundle\Controller\AbstractController class.

Instead of redirecting the user’s browser, this makes an “internal” sub-request and calls the defined controller. The forward() method returns the Symfony\Component\HttpFoundation\Response object that is returned from that controller:

  1. public function index($name)
  2. {
  3. $response = $this->forward('App\Controller\OtherController::fancy', [
  4. 'name' => $name,
  5. 'color' => 'green',
  6. ]);
  7. // ... further modify the response or return it directly
  8. return $response;
  9. }

The array passed to the method becomes the arguments for the resulting controller. The target controller method might look something like this:

  1. public function fancy($name, $color)
  2. {
  3. // ... create and return a Response object
  4. }

Like when creating a controller for a route, the order of the arguments of the fancy() method doesn’t matter: the matching is done by name.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.