What is the difference between redirect and forward in Zend framework
What is the difference between redire开发者_如何转开发ct 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:
- Zend Framework, what $this->_forward is doing
- http://osdir.com/ml/php.zend.framework.mvc/2007-09/msg00038.html
- http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Controller/Action/Helper/Redirector.php
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
The redirect action ends the current page process and redirects to another. All the context will change (new controller/action) as the browser receives a redirection. It connects to a new URL
Whereas the forward will stay on the same page, but will leave the context unchanged. You can see this as a function call. Your views will be loaded as usual.
精彩评论