views:

46

answers:

2

Possible Duplicate:
Zend Framework: Controller Plugins vs Action Helpers

I know what the difference is technically, and how to register a front controller plugin/action helper, but it would really help me if someone with more experience in zend framework could explain me the different use cases for the two (examples would be great).

I still have to learn a lot when working with zend framework and I guess it could make things more easy when I would know when to use an action helper rather then a front controller plugin and vice versa.

Thanks!

+1  A: 

A front controller plugin executes for every request, at specific stages in the MVC cycle. You can use it to perform work like checking whether a user is authenticated or logging requests to a database for analytics.

A controller action helper can also perform at different stages of the MVC cycle, though this isn't mandatory. The key difference between plugins and action helpers is that your controllers can interact with action helpers to change their behaviour, or use some on-demand functionality.

A plugin is often better for things that ALWAYS need to happen, while an action helper is useful for occasional tasks, like sending a JSON response.

An example for controller/helper hooks:

You have an action helper that checks at preDispatch whether a user is logged in and, if not, asks the user to log in. In your login controller you want an exception to this rule, or you'll loop infinitely. In the login controller's init method you can do the following, as the init() is called BEFORE preDispatch:

public function init() {
   $this->_helper->myHelper->setAuthenticationRequired(false);
}

This sets a boolean in the helper to skip the authentication check.

David Caunt
+1  A: 

A great ressource is this UML diagram: http://www.kitpages.fr/cms/site/tutoriaux/sequence_globale.jpg

You can see the calls to Plugins and then Helpers, and the yellow zone being the dispatching loop.

Don't forget that Helpers hooks (#17 and #22) won't be triggered if the helper has not been called/used, this is great and could save you time as unused process won't need to be initialized.

I mostly use:

  • Plugins for heavy logic required project wide (as Authentification, Acl, ...),
  • and Helpers for most specific tasks closer to the action (like sorting, filtering, pagination, json encoding, pdf download) avoiding duplication of code in many actions
Julien