Zend Framework

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);

Source: http://devzone.zend.com/article/3350-Action-Helpers-in-Zend-Framework

Note: As you’ve seen, it is complicated and bloated rather than elegant to create such helpers isn’t it? That is the bad side but also the good side of Zend Framework.

22 thoughts on “Creating Your Own Helper – Zend Framework”

  1. Hi,
    thanks for the example. Only one tiny issue, there is no <? php tag at the beginning of the class Dc_Helper_DaysInMonth . Believe it or not I spent 3 days troubleshooting why the example wasn't working until i found out. It might be a good idea to put one up there to avoid the pain to ppl who are just going to copy paste and try to make the example work. Otherwise thanks for the help.
    JR

  2. Some troubleshooting tips:

    If you get the error message:
    ———
    An error occurred
    Application error
    Exception information:

    Message: Action Helper by name DaysInMonth not found
    ———

    Check:

    The DaysInMonth.php file location: /library/Dc/Helpers/DaysInMonth.php

    Make sure you have the php opening tag as the first line of the DaysInMonth.php file.
    <?php
    (In case the comment submission mangles it: that should be a 'less than' followed by 'question mark' then the 3 letters 'php')

    Remember things are CaSeSeNsItIvE so make sure Dc is always correct.

  3. Hi J-R and Insti,

    I reviewed my spam comments and saw yours and I think it was akismet mistake (which I enabled a year ago). I disabled it now.

    Yes, the sample above lacks the <php tag. Sorry, I’m too lazy and don’t have enough time to review my posts. Of course that is a simple missing piece of tag that every PHP developer should not miss.

  4. Hi
    just one question where to put in bootstrap :
    Zend_Controller_Action_HelperBroker::addPrefix(‘Dc_Helper’);
    please clear it?

  5. Hi behrang, I have reviewed my old codes:

    You put that line using any init method at bootstrap, ex:

    protected function _initActionHelpers()
    {
    Zend_Controller_Action_HelperBroker::addPath(
    APPLICATION_PATH . “/controllers/helpers”
    );

    /**
    * Setup the Custom Helpers
    */
    Zend_Controller_Action_HelperBroker::addPrefix(‘Dc_Helper’);
    }

  6. I suppose You meant getDaysInMonth not getGaysInMonth : ). But that’s not importatnt. Thank You for tutorial.

  7. great tutorial. This is one of the best zend tutorials I’d ever read. Usually, zend geeks tend to be very bad teachers, and that’s in addition to the nightmare of the zend documentation.

    But I don’t get what the purpose of the $pluginLoader; and $this->pluginLoader = new Zend_Loader_PluginLoader(); is for in this code?

  8. Probably a way to use another pluginLoader aside from the default pluginLoader. By the way, I just followed what you said “nightmare zend docs” 😀

    But don’t trust the docs, read the code instead.

  9. Hi Dear,

    It is very good tutorial and I am very impressing by adding helper at run time in bootstrap file. I have read your all previous comments.

    I got a problem when I use it with getMessages() function it give output after refresh the page but when I use getCurrentMessage() function it give output on rendering the page.

    Can you tell me that why the page is not showing message using getMessage() function on rendering time.

    I have used ajax call in my controller action.

    Thanks for your nice tutorial…?

Leave a reply

Your email address will not be published. Required fields are marked *