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 Answers
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.

- 563
- 5
- 15
-
Best answer right here. The overhead of modules is not worth it, especially when you need the function in template files. – jmargolisvt Oct 20 '16 at 14:15
-
It's probably important to say. (although it seems this should go without saying...) This is a great TEMPORARY solution, you wouldn't want to actually have a quick debugging function accessible anywhere. This would be used during dev to find those pesky object values and that would be it. Going through the overhead of module creation and Helper setup is definitely good for production use and a number of other reasons, scalability for example. – Nathaniel Rogers Apr 05 '17 at 04:01
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

- 26,809
- 13
- 80
- 104
-
thanks, can you send me a link that shows me how to create Helper classes? I keep getting this error Fatal error: Class 'Mage_PAP_Helper_Data' not found in /srv/www/web.com/dev_html/app/Mage.php on line 520 .... I'm pretty sure I've set up the module, just dont know why helpers aren't working – John Jan 26 '11 at 22:58
-
John, you must set your helper at config.xml, put this inside
: ` – Mateus Neves Jul 30 '14 at 18:18 `Your_Helper_Class
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.

- 76,472
- 17
- 159
- 346

- 144
- 4
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/

- 1,312
- 4
- 23
- 48