Helpers in ZF(Zend Framework) are often confusing for newbies.
Purpose of writing this article is to make it easy to understand the helpers.

ZF provides two types of helpers
1. Action Helper
2. View Helper

As you can guess by type action helper is concerned with actions (controllers) and view helper is concerned with views scripts.

ZF comes with built in helpers for both action and views but we may need to create custom helpers according to our needs.

So lets start with Action Helpers, to understand we take an example of blog
lest suppose we have a blog with two controllers
1. Admin controller
2. Public controller
and in each controller I have to check for authentication either user is logged in or not, what would be the easy solution? writing an auth function in each controller would do the job like

class AdminController extends Zend_Controller_Action
{
  public function auth()
  {
    /**
     * write some logic here
     */
  }
}

class PublicController extends Zend_Controller_Action
{
  public function auth()
  {
    /**
     * write some logic here
     */
  }
}

But this is not good way to handle as same function is repeated in both controllers, I guess I need to write only one function and use it in both controllers, for this purpose I am going to write an action helper

My_Action_Helper_Auth extends Zend_Controller_Action_Helper_Abstract
{
  function auth()
  {
    /**
     * wirte your code here
     */
  }
}

Now in my controllers I just need to call the auth helper to check the authentication


class AdminController extends Zend_Controller_Action
{
  public function init()
  {
    if (!$this->_helper->auth()) {
      //write your logic
    }
  }
}
Advertisements