In this post, we will see why and how should we use helpers. Helpers in Magento are classes that contains methods. We can use helpers anywhere in Magento.

Helpers are singleton objects, i.e. whenever you try to access your helper, you will get the same object ( on first time call, this object gets created ).

Let’s see, how we can create an helper.

Creating helper

  1. First of all, you should have created a module. To see how to create a module, click here
  2. Now create a folder Helper in your module
     

    Test\Basic\Helper
  3. Next, create a new file named Data.php ( this is default for helpers, you can also give other names )
  4. Add following code in it:
     

    <?php
    class Test_Basic_Helper_Data extends Mage_Core_Helper_Abstract{
        public function add($x, $y){
            return $x + $y;
        }
    }

     
    Again, the name of the class should be in the format: Namespace_Modulename_Helper_Filename

  5. Next, we need to tell Magento where to find our helpers. For this, we will be editing our etc\config.xml file. Make sure your file looks like this:
     

    <?xml version="1.0" ?>
    <config>
        <modules>
            <Test_Basic>
                <version>1.0</version>
            </Test_Basic>
        </modules>
        <global>
            <helpers>
                <basic>
                    <class>Test_Basic_Helper</class>
                </basic>
            </helpers>
        </global>
    </config>

Using helper
Open any existing template ( phtml ) file and add following code:

<?php
    $basicHelper = Mage::helper('basic/data');
    echo $basicHelper->add(4,5);
?>

 
Since helpers find Data.php by default, we can also write the above code as:

<?php
    $basicHelper = Mage::helper('basic');
    echo $basicHelper->add(4,5);
?>

 
Refresh your cache and reload your page.

That’s it, how easy it is to use helpers.