6

I'm looking for a right way to create global variables in Magento that I can use it on every view page. I have some solution in mind but I don't if it's good enough.

  1. Create a module which provides a global configuration - I don't prefer this much since I rather work with php array rather than xml, just my stupid taste.

  2. Override the base block to have one more utility function

It's just my thought, any other suggestions are welcome :)

1
  • What does the variable contain or do? Is it numeric? Is it an HTML string?
    – philwinkle
    Commented Feb 11, 2013 at 18:08

2 Answers 2

10

You could create a session variable to have a persistent state over several requests like this:

$session = Mage::getSingleton("core/session");
$session->setData("your_variable", "your value");
// ...
// Now you can retrieve your data elsewhere or even after the next request:
$session = Mage::getSingleton("core/session");
$yourVariable = $session->getData("your_variable"); // will be "your value"

You can also create your own session model, if you want to avoid the core/session namespace.

2
  • 1
    And where should I declare above session vars. if I have to use it 100 times on multiple pages? Commented Sep 16, 2015 at 9:29
  • @PratikCJoshi, they can be used anywhere within PHP tags in Magento. If you have to use them 100 times in multiple pages, there must be some better alternative for that, try asking a separate question for that.
    – Prateek
    Commented Oct 5, 2015 at 8:55
6

Use the built-in Custom Variables functionality which gives you editable values from the admin:

http://www.magentocommerce.com/knowledge-base/entry/creating-custom-variables

When calling from your template:

Mage::getModel('core/variable')->loadByCode('my_custom_var')->getValue('plain');

When calling from anywhere else (CMS, emails, etc.):

{{customVar code=my_custom_var}}

Source:

https://stackoverflow.com/questions/6221054/magento-how-do-i-access-custom-variables-in-php

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.