magento - create a global function

6.7k views Asked by At

I want to create a function that can be accessed by all *.phtml files. Where should i place this function in the magento framework?

4

There are 4 answers

2
Joe Mastey On BEST ANSWER

You should create a module and a helper class in that module (Usually MyCompany_Mymodule_Helper_Data by default). Then, add your function to that helper class. You can get to that function in your PHTML like this:

Mage::helper("mymodule")->someFunction();

Hope that helps!

Thanks, Joe

2
Billy On

For down and dirty things, you can always define it in index.php. for example, I always put this function there:

function dumpit($obj)
{
  print '<pre>';
  print_r($obj);
  print '</pre>';
}

Then you can quickly call this routine from anywhere, without having to remember all the other overhead function names to get at the helper.

0
Anand Singh On

C:\wamp\www\mydirectory\app\code\core\Mage\Page\Helper\Data.php is my path. I used print_r function as the pr() function.

Put it in Data.php as below.

class Mage_Page_Helper_Data extends Mage_Core_Helper_Abstract
{
    function pr($data) 
    {
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }
}

where page is mymodule.

Call it from any .phtml file with

Mage::helper("page")->pr($abcd);

Hope it helps.

0
Joe Riggs On

For anyone who's interested I put together a short tutorial on how create a global function in Magento : http://joe-riggs.com/blog/2011/06/create-global-function-in-magento/