user1400
user1400

Reputation: 1409

What is the difference between redirect and forward in Zend framework

What is the difference between redirect and forward in Zend framework?

When we should use redirect and when should we use forward?

Upvotes: 38

Views: 23762

Answers (6)

user187291
user187291

Reputation: 53940

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. ;)

Upvotes: 68

Gordon
Gordon

Reputation: 316999

_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:

Upvotes: 55

pinkgothic
pinkgothic

Reputation: 6179

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.

Upvotes: 4

tawfekov
tawfekov

Reputation: 5122

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

Upvotes: 1

Rodolphe
Rodolphe

Reputation: 497

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.

Upvotes: 0

Andy Shellam
Andy Shellam

Reputation: 15535

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.

Upvotes: 2

Related Questions