The Magento registry allows you to share information anywhere in your Magento application as if they are static function. Magento’s registry acts a lot like Zend’s, and basically allows the creation of new variables which can be accessed anywhere within your Magento store in a “global” fashion. As the registry is a static function, the Magento registry can be called directly without the overhead of having to instantiate an object.
The registry has two basic functions, which give a developer the ability to register or un-register variables, and then a third to retrieve data.
register()
– registers your variables which can seemingly only be an integer, string or an array.
unregister()
– unregisters (removes) your registered variable.
registry()
– used to retrieve registered variables.
Registering data in the Magento registry
To register data, you simply need to call the register
function, like so:
1 |
Mage::register('my_variable', $myvariable); |
Removing data from the Magento registry
To remove data, you simply need to call the unregister
function, like so:
1 |
Mage::unregister('id'); // unregisters the id variable |
How to retrieve a variable from the Magento registry
Retrieving variables from the Magento registry is straight forward too – simply call teh registry
function.
1 |
$registry = Mage::registry('id'); // retrieves id variable from the registry |
Magento regularly uses registry entries itself so that it doesn’t have to hammer the database for every request.
Examples of this include:
Retrieving page information for a CMS page.
1 2 3 |
$page = Mage::registry('cms_page'); echo $page->getTitle(); echo $page->getContent(); |
Retrieving data from a category page.
1 2 |
$_category = Mage::registry('current_category'); echo $_category->getName(); |
Image Credit: dok1
Comment or tweet @douglasradburn