This post covers basic tasks that you may want to do within controller: forwarding to different actions, redirecting, and displaying 404 page. Once again, I will show how this tasks can be achieved in both ZF1 and ZF2.
"Forwarding" means jumping from one action to another.
In Zend Framework 1 "forward" is implemented as a function within
// forward to "login" action of UserController return $this->forward('login', 'user');
Zend Framework 2 comes with Forward plugin. Usage is very similar:
// forward to "login" action of UserController return $this->forward() ->dispatch('Application\Controller\User', array('action' => 'login'));
Application\Controller\User must be defined in application config
There are two differences between ZF1 and ZF2:
- When forwarding to different action within the same controller, ZF1 will create new instance of controller class. It means that all variables within this controller will be lost. ZF2 does the opposite - if controller object is already created, your data will be intact.
You can think of ZF1's
forwardas a function that sets new action to be executed after current one. So, if you forget to add return
statement, your current action won't stop running. ZF2's
forwardwill dispatch new action instantly.
Redirecting works in a similar way in both frameworks. Only difference is the syntax.
// redirect to URL return $this->redirect('http://any-url-will-do.com'); // redirect to route return $this->_helper->redirector->gotoRoute( array('page' => 'about-us'), 'view-static-page' ); // redirect to different action & controller return $this->_helper->redirector->gotoSimple('action', 'controller');
// redirect to URL return $this->redirect()->toUrl('http://any-url-will-do.com'); // redirect to route return $this->redirect()->toRoute( 'view-static-page' array('page' => 'about-us'), );
Both Zend Frameworks will automatically show "page not found" when URL doesn't match any defined route, or when requested action (or controller) doesn't exist. Sometimes you may want to trigger this page manually (for example this blog application will show 404 page when you type http://dev.mateusztymek.pl/blog/invalid-article in the URL).
404 page in ZF1 is usually handled by
Easiest way to get there is to throw an exception:
throw new Zend_Controller_Action_Exception('404 Page not found', 404);
Alternatively (I was actually using this method in most of my projects), you could forward to "special" action dedicated to handling 404s:
// forward to "page-not-found" action of ErrorController $this->forward('page-not-found', 'error');
Zend Framework 2 doesn't come with
ErrorController. Instead, it registers event listeners
that will render "page not found" view script when response is about to return 404 code.
It can be triggered with this one-liner: