Monday, March 16, 2015

Creating Your Own Helper – Zend Framework

In Zend Framework, most of the important functions are built into the framework. Most of them are in the View Helpers or Action Helper. But in big projects, you will always need to inject some functionality that are too small to create a class/plugin.
You can always create a protected function inside a controller, but what if that function is needed in more than one controller? Creating a base controller that you will extend later will only create troubles when controllers don’t initialize properly or if not all controllers need those functionalities.
So, here is how to create your own helper (of course this can be found on the zend framework online manual):

1. Create the helper directory structure

Your helper class name must be compatible with Zend’s naming conventions to allow Zend_Loader to load it automatically. Your helper must be placed on a directory that is set in include path. In my case I have only one included path and that is the library directory, so I placed them there:
  • library/Zend/[Zend Library]
  • library/Dc/Helper/[My Helpers] - this is where my helpers located

2. Tell Zend Framework the location of your helpers

So that Zend Framework includes your helpers, add this line to your bootstrap:

/**
 * Setup the Custom Helpers
 */
Zend_Controller_Action_HelperBroker::addPrefix('Dc_Helper');
That way, the folder Dc/Helper/ is read along with other default helper paths when loading a helper.

3. Create the helper

Now, it’s time to create the actual helper. To create the helper, you must extend Zend_Controller_Action_Helper_Abstract and do some initialization on the constructor.
The helper below is called DaysInMonth, which returns the number of days in a certain month where month and year is given.

/**
 * Action Helper for finding days in a month
 */
class Dc_Helper_DaysInMonth extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * First entry is for January
     */
    protected $daysInMonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
     
    /**
     * @var Zend_Loader_PluginLoader
     */
    public $pluginLoader;
 
    /**
     * Constructor: initialize plugin loader
     *
     * @return void
     */
    public function __construct()
    {
        $this->pluginLoader = new Zend_Loader_PluginLoader();
    }
 
    /**
     * Returns the number of days in a given month + year
     *
     * @param int $month
     * @param int $year
     * @return int
     * @throws Exception
     */
    public function getDaysInMonth($month, $year)
    {
        if ($month < 1 || $month > 12)
        {
            throw new Exception('Invalid month ' . $month);
        }
    
        $d = $this->daysInMonth[$month - 1];
    
        if ($month == 2)
        {
            // Check for leap year
            // Forget the 4000 rule, I doubt I'll be around then...
         
            if (($year % 4) == 0)
            {
                if (($year % 100) == 0)
                {
                    if (($year % 400) == 0)
                    {
                        $d = 29;
                    }
                }
                else
                {
                    $d = 29;
                }
            }
        }
     
        return $d;
    }
     
    /**
     * Strategy pattern: call helper as broker method
     *
     * @param  int $month
     * @param  int $year
     * @return int
     */
    public function direct($month, $year)
    {
        return $this->getDaysInMonth($month, $year);
    }
}
The public function direct is the entry point of your helper. It just accepts the parameters then call the function to get the days in a month. That is called Strategy Pattern.
You’ll notice that what I was really trying to create was just the function getDaysInMonth.

4. Call the helper inside your controller

To call my newly created helper, here it is (inside the controller)

$days = $this->_helper->daysInMonth(4, 2009);

No comments:

Post a Comment