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

后端 未结 1 1372
误落风尘
误落风尘 2020-12-09 22:12

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 look

相关标签:
1条回答
  • 2020-12-09 22:50

    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');
      }
    }
    
    0 讨论(0)
提交回复
热议问题