What is the difference between redirect and forward in Zend framework?
When we should use redirect and when should we use forward?
Imagine you get a phone call in the office. Someone wants to talk to sales. If you say "please call 123456" and hang up, this is redirect . If you say "wait a minute" and just transfer the call to them, this is forward. ;)
_forward()
just forwards everything to another controller action, while _redirect()
sends a header, meaning you create a new HTTP Request and go through the entire dispatch process with it.
For instance, if you call up http://example.com/foo/bar you'd call the foo
controller and bar
action. If you forward inside the bar
action to the baz
action, e.g. within the very same request, the browser would still be on the same URL, while when doing a redirect, ZF would instruct the browser to load http://example.com/foo/baz.
Essentially, _forward()
does
$request->setActionName($action)
->setDispatched(false);
while _redirect()
does
$this->_helper->redirector->gotoUrl($url, $options);
I usually do redirects when I want to prevent reload a page resulting in reposting form data.
See these:
You would use _forward() for cases where you want the URL to stay the same - though beware, it does mean whatever base controller class you're using is called twice.
That may seem obvious or trivial, but if not kept in mind, can really screw up your application design, given that intuitive understanding of the flow is that one request calls one controller instance. E.g. it means request-scope singletons have to be declared as static
, or _forward() will break them.
I would guess that a redirect sends a 301/302 back to the browser with a new URL, while a forward simply "forwards" the request to a different controller action internally but keeps the URL the same so the browser doesn't know any different.
1-redirect create a new response with header() information [302 Found or 301 == Moved permanently] and its will get to the dispatch cycle once again
2-forward change the execution flow to that new request without re enter the dispatch process again
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With