Is it possible to forward data to another controller/action in Zend 2?

Raekye picture Raekye · Jan 6, 2013 · Viewed 17k times · Source

I think a common problem is trying to forward (post) data to another page. Normally, I'd resort to sessions to pass data between pages, but this forward helper in Zend looks like it has potential. Is there any way to get information about a forward request? Like ask for the forwarder (and it'd return null normally when there's no forwarder)?

And if there's no current implementation, is it possible? It'd be a fun project, and something I've wanted forever anyways. (I'm also currently using my own BcryptDbTableAuth class until I find a better solution).

By the way, I'm not talking about adding request params. It should be invisible to the user. And I'm still investigating variable routes (Wildcard is supposed to do the trick but I keep getting "route cannot be matched"... will drill on that a bit more)

Answer

Jurian Sluiman picture Jurian Sluiman · Jan 6, 2013

There are two options to "forward". Understand php is as server side language a processor to grab an incoming request and return a response.

That said, the first "forward" uses in-framework forwarding. This means there is only one request and one response. Internally the framework calls one controller action and then another one. Zend Framework calls this method forward.

The second "forward" is a real redirect, where the first response contains a Location header and the 302 http status code. This results in a second request and consecutively in a second response. Zend Framework calls this method redirect.

So with above, the forward you talk about in your question does not involve any sessions or route match parameters, since the second call to an action is within the same php process, so all variables are already known.

Forward example

An example to forward is to use the forward controller plugin:

class MyController
{
  public function myAction()
  {
    return $this->forward()->dispatch('MyModule\Controller\Other', array(
      'action' => 'other',
      'foo'   => 'bar',
      'baz'   => new Bat()
    ));
  }
}

To access:

class OtherController {
    public function otherAction()
    {
        $foo = $this->params()->fromRoute('foo');
    }
}

As you might note, it is possible to add additional parameters to the forward call including real objects.

Redirect example

One option is to use the route parameters, so you capture data in the url you send back. Because you say you don't want that, you have to use a session for that:

use Zend\Session\Container;

class MyController
{
  public function myAction()
  {
    $session = new Container('MyContainer');
    $session->foo = 'bar';
    $session->baz = 'bat';

    return $this->redirect()->toRoute('my/other/route');
  }
}