Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
user1400 Avatar asked Mar 31 '10 07:03

user1400


5 Answers

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

like image 151
user187291 Avatar answered Oct 18 '22 06:10

user187291


_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
like image 42
Gordon Avatar answered Oct 18 '22 07:10

Gordon


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.

like image 40
pinkgothic Avatar answered Oct 18 '22 05:10

pinkgothic


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.

like image 2
Andy Shellam Avatar answered Oct 18 '22 05:10

Andy Shellam


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

like image 1
tawfekov Avatar answered Oct 18 '22 07:10

tawfekov