Create helper classes in Magento

Assume we have helloworld module under MageHome/app/code/local/MyExtendions/Hellworld.
1. Add the below in within the global tag in MageHome/app/code/local/MyExtendions/Hellworld/etc/config.xml
[code language=”xml”]
<helpers>
<helloworld>
<class>MyExtensions_Helloworld_Helper</class>
</helloworld>
</helpers>
[/code]

2. Create a file MageHome/app/code/local/MyExtendions/Hellworld/Helper/Data.php
[code language=”php”]
<?php
class MyExtensions_Helloworld_Helper_Data extends Mage_Core_Helper_Abstract
{
public function helloHelper()
{
echo "Hello, I am a helper function!!!";
}
}
[/code]

3. Create a file MageHome/app/code/local/MyExtendions/Hellworld/Helper/Calculator.php
[code language=”php”]
<?php
class MyExtensions_Helloworld_Helper_Calculator extends Mage_Core_Helper_Abstract
{
public function sum($a, $b)
{
return $a + $b;
}

public function substraction($a, $b)
{
return $a – $b;
}

public function multiplication($a, $b)
{
return $a * $b;
}

public function division($a, $b)
{
return $a / $b;
}
}
[/code]

Now, we can use these helper functions in template files, controllers, models or anywhere else in Magento like this:
[code language=”php”]
Mage::helper(‘helloworld’)->helloHelper();
Mage::helper(‘helloworld/Calculator’)->sum(2,3);
Mage::helper(‘helloworld/Calculator’)->substraction(10,3);
Mage::helper(‘helloworld/Calculator’)->multiplication(5,3);
Mage::helper(‘helloworld/Calculator’)->division(9,3);
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search