Pages

Monday 23 June 2014

Magento Developper’s Guide (Lesson 12) – The Helpers in magento

This tutorial is the 12th of many tutorials , you will now learn how to create your own helper in Magento. If you have not read the first articles yet, I strongly advise you to do so. We have previously created a plugin, we will now learn how to use a helper!


What is a Helper?

As the name implies a « helper » is something that is right for you ! It is an object that will contain practical functions for you and you can call it from anywhere, you just load your helper to use it. For example:

$helper = Mage::helper('monhelper');
 
Note that this call is actually equivalent to:
 
$helper = Mage::helper('monhelper/data');
 
Indeed, it is the default helper « data » wich is called.

Create your own Helper

As you are now used to, it starts by declaring it in the config.xml of your plugin, do that in <global> and after </blocks>

<helpers>
   <test>
          <class>Easylife_Test_Helper</class>
    </test>
</helpers>
 
 


Then creates the folder and the file app/code/local/Easylife/Test/Helper/data.php function wich will contains the function bytwo($ nbr) with a number as an argument and returns that number multiplied by two. A helper is an object that extends the core class Mage_Core_Helper_Abstract.
 
<?php
class Easylife_Test_Helper_Data extends Mage_Core_Helper_Abstract{
   public function bytwo($nbr){
        return $nbr*2;
   }
}
 
Now in/app/code/local/Easylife/Test/Block/monblock.php we change the function by:
 
<?php
class Easylife_Test_Block_Monblock extends Mage_Core_Block_Template
{
      public function methodblock()
      {
            $helper = Mage::helper('test');
            return '2*2 = '.$helper->bytwo(2);
      }
}
 
Now when we go on yoursite.com/index.php/test/index/, we see that it works!

Here we are ! you understand how to create a helper on magento, I invite you to practice, the only way to improve yourself ;) If you have any questions, feel free to leave a comment.

You want to help me? 

Share this article on twitter, do an article on this series of tutorials on your blog, tell your friends, participate in the comments and return to this site ;)
 

Find the summery of this tutorial

No comments:

Post a Comment