Quantcast
Channel: Josh Pratt – Prattski | Magento & Web Development
Viewing all articles
Browse latest Browse all 14

Using The Magento Registry (Mage::register)

$
0
0

I was recently working on a module, and I noticed that another 3rd party module had some very poorly-written code in it that was messing up an after_save event that I was needing to work with. I therefore had to find a way to store some data temporarily to prevent duplicates (the issue that was encountering).

I initially thought I could use the session. However, the functionality I was working with is occasionally fired off via command line, so that wasn’t going to work. So I then remembered the Magento Registry and ended up using that, which worked great.

To be honest, I don’t know the technical details as to how/where the Magento registry stores its data. I do know that it is not stored in a session, in the database, or in files. Somehow, it is stored in the application’s memory. Once your script is done running, whatever you had stored in the registry is gone, so there is no need to worry about clearing it out (unless the script you are running is storing large objects in the registry and is looping through a lot of data). In that case, you’ll want to unregister your entries when you are done with them.

You can add pretty much anything into the registry, from a product object, to an array, to a simple string.

Adding To The Registry:

The method to add to the registry is as follows. It takes two parameters. The first is the unique key you would like to give your registry entry. The second is the data you are wanting to store.

Mage::register('name-of-registry-key', $your-data);

Getting Data From The Registry:

When you are ready to retrieve the data you have stored, use the following method:

$var = Mage::registry('name-of-registry-key');

Removing From The Registry

When and if you are ready to remove the data from the registry, there is a method to unregister it. This may be important to you, especially if you are using the registry in a loop and you are wanting to set the same registry key name more than once. The Mage::register() method will not let you set a key if it is already set.

Mage::unregister('name-of-registry-key');

If you are able to better explain how/where Magento stores the registry data, please let me know. I couldn’t really find out a good explanation of that anywhere on the web (from my brief search).


Viewing all articles
Browse latest Browse all 14

Trending Articles