What is the difference between redirect and forward in Zend framework?
When we should use redirect and when should we use forward?
What is the difference between redirect and forward in Zend framework?
When we should use redirect and when should we use forward?
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
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. ;)
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.
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._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 andbar
action. If you forward inside thebar
action to thebaz
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()
doeswhile
_redirect()
doesI usually do redirects when I want to prevent reload a page resulting in reposting form data.
See these:
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.