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

      <helpers>
        <helloworld>
            <class>MyExtensions_Helloworld_Helper</class>
        </helloworld>
      </helpers>

2. Create a file MageHome/app/code/local/MyExtendions/Hellworld/Helper/Data.php

<?php
class MyExtensions_Helloworld_Helper_Data extends Mage_Core_Helper_Abstract
{
	public function helloHelper()
	{
		echo "Hello, I am a helper function!!!";
	}
}

3. Create a file MageHome/app/code/local/MyExtendions/Hellworld/Helper/Calculator.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;
	}
}

Now, we can use these helper functions in template files, controllers, models or anywhere else in Magento like this:

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

Search within Codexpedia

Custom Search

Search the entire web

Custom Search