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.

This entry was posted in Zend Framework and tagged , , , , . Bookmark the permalink.

Related Posts

22 Responses to Creating Your Own Helper – Zend Framework

  1. Bhaskar Rabha says:

    Simple n useful. Thanks.

  2. Lysender says:

    Thanks for dropping by bro! 🙂

  3. Ben says:

    Very nice small tutorial how to make Action helpers! As Bhaskar said: simple and useful! Thanks.

  4. J-R says:

    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

  5. Insti says:

    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.

  6. Lysender says:

    Thanks for dropping by Ben.

  7. Renato says:

    Thats exactly what i was looking for!
    I knew that existed a simplified way to do that

  8. Lysender says:

    Actually, I just did what devzone suggested and it works!

  9. Lysender says:

    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.

  10. Behrang says:

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

  11. Lysender says:

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

  12. Pingback: Creating View Helpers – Zend Framework | Lysender

  13. Andrzej Nowak says:

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

  14. lysender says:

    @Andrzej:

    Oh snap! I will fix it next week, I really got a slow connection here.

  15. Awesome! Better explained than in ZF reference manual 😀

  16. Pingback: “Helpers” for Zend Framework — What are these creatures? « Zend Framework newbie

  17. Arvind says:

    found it useful
    thanks !!

  18. Blal says:

    Nice explanation.. I am a beginner and it helps me a lot. Thanks 🙂

  19. okeyxyz says:

    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?

  20. lysender says:

    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.

  21. Nirmal Ojha says:

    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…?

  22. Nguyen Thanh says:

    Thanks!

    It really helps me a lot.

    //Sorry i’m bad English.

Leave a Reply

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