PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Pre- and Post-Dispatch Hooks

Zend_Controller_Action specifies two methods that may be called to bookend a requested action, preDispatch() and postDispatch(). These can be useful in a variety of ways: verifying authentication and ACL's prior to running an action (by calling _forward() in preDispatch(), the action will be skipped), for instance, or placing generated content in a sitewide template (postDispatch()).

Usage of init() vs. preDispatch()

In the previous section, we introduced the init() method, and in this section, the preDispatch() method. What is the difference between them, and what actions would you take in each?

The init() method is primarily intended for extending the constructor. Typically, your constructor should simply set object state, and not perform much logic. This might include initializing resources used in the controller (such as models, configuration objects, etc.), or assigning values retrieved from the front controller, bootstrap, or a registry.

The preDispatch() method can also be used to set object or environmental (e.g., view, action helper, etc.) state, but its primary purpose is to make decisions about whether or not the requested action should be dispatched. If not, you should then _forward() to another action, or throw an exception.

Note: _forward() actually will not work correctly when executed from init(), which is a formalization of the intentions of the two methods.

Zend Framework