Magento Events

When it comes to extending Magento core functionality you have two options - override core classes or use event-driven architecture. The major disadvantage of first is that you can override class only once, so if you want to override it in multiple modules you are soon going to find yourself in dependency hell. Event-driven architecture allows you to keep loose coupling without losing the flexibility of extending Magento modules.

When you want to use Magento event-driven architecture you must know basically two things - how to dispatch an event and how to catch it.

Dispatching events

Within Magento you can dispatch an event as simple as by calling Mage::dispatchEvent(...) method, for example:

 Mage::dispatchEvent('custom_event', array('object'=>$this));

This methods accepts two parameters - event unique identifier and associative array of data that is set as Varien_Event_Observer object data, so in fact passed to event observers.

Catching events

Catching events is a little bit more complex than dispatching. You have to use existing custom module or create a new one. In the minimal case the module file tree should look like this:

  

Within config.xml you have to add a definition of event observer. Which of the main config.xml file sections (frontend, adminhtml) should contain this definition depends on the scope you want your observer to work on. Here is the example of definition:

<events>
      <custom_event> <!-- identifier of the event we want to catch -->
        <observers>
          <custom_event_handler> <!-- identifier of the event handler -->
            <type>model</type> <!-- class method call type; valid are model, object and singleton -->
            <class>baobazacustommodule/observer</class> <!-- observers class alias -->
            <method>customObserverAction</method>  <!-- observer's method to be called -->
            <args></args> <!-- additional arguments passed to observer -->
          </custom_event_handler>
        </observers>
      </custom_event>
</events>

Xml above should be self-explanatory. I will just explain that for type model and object are equal in behavior and mean that object of a class will be instantiated using Mage::getModel(...) method, and singleton means it will be instantiated using Mage::getSingleton(...) method.

Observer.php file should contain relevant observer class. There is no interface nor need to extend any class for observer classes. The method though should accept one parameter which is the object of Varien_Event_Observer class. This object is the link between dispatcher and event handler. It inherits from Varien_Object so has all required getters handled magically. For example:

class Baobaz_ACustomModule_Model_Observer
{
  public function customObserverAction(Varien_Event_Observer $observer)
  {
    $object = $observer->getEvent()->getObject(); // we are taking the item with 'object' key from array passed to dispatcher
    $object->doSomething();

    return $this;
}

Default events

Magento implements lot of events. You can find list of them here. What you may miss reading this list, and what was spotted on MageDev blog, Mage_Core_Model_Abstract by default dispatch some special events. Those are:
 

event identifier event parameters
model_save_before 'object'=>$this
{_eventPrefix}_save_before {_eventObject}=>$this
model_save_after 'object'=>$this
{_eventPrefix}_save_after {_eventObject}=>$this
model_delete_before 'object'=>$this
{_eventPrefix}_delete_before {_eventObject}=>$this
model_delete_after 'object'=>$this
{_eventPrefix}_delete_after {_eventObject}=>$this
model_load_after 'object'=>$this
{_eventPrefix}_load_after {_eventObject}=>$this

 

{_eventPrefix} means the value of $_eventPrefix variable and {_eventObject} means the value of $_eventObject variable. All classes inheriting from Mage_Core_Model_Abstract should override these variables to create specific events being dispatched. For example for catalog cagetory these variables take following values: $_eventPrefix = 'catalog_category';  $_eventObject = 'category';

20 comments on "Magento Events"

valugi's picture
valugi (visitor) - Tue, 02/02/2010 - 18:16:

baobazacustommodule/observer

Is this correct or it should be something like:

baobaz/acustommodule/observer
or
baobaz_acustommodule/observer

I cannot seem to make this work. Thanks

Lucjan Wilczewski's picture
Lucjan Wilczewski - Wed, 03/02/2010 - 12:09:

baobazacustommodule/observer is a typical model class alias, so the first part - baobazacustommodule - is what you have defined in <models> section of config.xml as alias for Baobaz_ACustomModule_Model (points at path /Baobaz/ACustomModule/Model), and second part - observer - is telling the name of the file within /Baobaz/ACustomModule/Model folder, which is Observer.php.

An example to make the explanation clear:
<models>
  <baobazacustommodule>
    <class>Baobaz_ACustomModule_Model</class>
  </baobazacustommodule>
</models>

bad credit student loans's picture
bad credit student loans (visitor) - Tue, 11/01/2011 - 14:16:

Best Wishes, http://blog.bitcomet.com/post/304712/ >bad credit student loans now, [url= http://blog.bitcomet.com/post/304712/ ]bad credit student loans now[/url], %-]],

Chance's picture
Chance (visitor) - Thu, 28/07/2011 - 01:22:

I've been developing a new online database driven website for a customer. I've built in a Magento event driven code that prints to various printers, I've been using just a basic wireless dell 5110cn to run testing and it's not working. One of the other sites says that I need to look at the parameters that I have set. Any ideas without me sending over the code?

Anonymous's picture
Anonymous (visitor) - Mon, 08/08/2011 - 12:30:

There are plenty of information about this topic in the net & some are definitely better than others.
best forex robots

Jasmeen's picture
Jasmeen (visitor) - Tue, 16/08/2011 - 09:52:

I am really impressed by this blog! Very clear explanation of issues is given and it is open to everyone. I have read your post, really you have provided such a great information about it Attic Conversion

office 2010's picture
office 2010 (visitor) - Thu, 13/10/2011 - 03:38:

Einfuhrung from Office 2007 death revolutionaren yangon Microsoft Office 2007 fruhen nest Tastatur through yangon Office 2007 Download vergessene chart Navigationsmethode Office 2007 Professional holiday with his MS Office 2007 angestaubt wenig vein Office 2007 Key, but dennoch China and buy microsoft office 2007 Zwecken Programmen modernen also Download Office 2007 unhappy with praktisch selten erst Microsoft Office 2007 Professional, analysing Zeitsparer purchase microsoft office 2007 echter vein.Microsoft Office 2010 Many people use Office 2010 to help their work and life Microsoft office 2011.


This is the Download Office 2010 art Kontrolle winter altmodisch just and MS Office 2010, and not unsinnig sieht nest Office 2010 Key. Here are written by Office 2010 Download Tastatur enorm erreichen physician Office 2010 Professional. I eventuell Microsoft Office 2010 Download death Anwendungen many buy microsoft office 2010 Tastenkommandos Buy Windows 7 relativ flag-bearing Windows 7 angewiesen bigger worry, weniger Microsoft Windows 7 die interface anxiety.Win 7 is such a good assistant of the Download Windows 7.
http://softwarestockss.blogspot.com


http://software-stocks.com

Anonymous's picture
Anonymous (visitor) - Thu, 20/10/2011 - 12:14:
Anonymous's picture
Anonymous (visitor) - Wed, 26/10/2011 - 12:50:

Observer.php file should contain PMI-001 relevant observer class. There is no interface nor need to extend any class for observer classes. 642-661 The method though should accept one parameter which is the object of Varien_Event_Observer class. This object is the 70-515 link between dispatcher and event handler. It inherits from Varien_Object so has all required getters handled magically.

monclerit2011's picture
monclerit2011 (visitor) - Fri, 28/10/2011 - 03:25:

Giubbotti Moncler sono un buon modo per manteneremoncler outlet il vostro senso

della moda canada goose outletvive іn ogni stagione. Quando si indossano

giubbotti Moncler caldo ed elegante, si non può non innamorarsi di fiducia e personalità che giubbotti Moncler portare a voi!

Come per una famosa marca,belstaff outlet Moncler è continuare a muoversi nel

mondo della moda, belstaff outletcontinua a lanciare sempre più gardgets

Moncler moda per soddisfare le esigenze della moda più persone

canada goose jakke's picture
canada goose jakke (visitor) - Wed, 02/11/2011 - 02:43:

Farver canada goose jakke op beidafupi jacket i filmindustrien canada goose, såsom the Dark Knight, x-mænd, og canada goose outlet underverdenen, og I am legend belstaff outlet og har for nylig udgivet selvmord.I dag, efteråret belstaff på ny hylden, ikke kun mode, men vil holde Canada Goose M?nd Vest dig tilsluttet på legender af læder.Varmen sommer, varme, vanskeligheder i bevare!Heldigvis efteråret nærmer Canada Goose Original sig, foruden Ishockey og vinter øl kan tiltrække øjet, en frisk indtryk af læder jakke!Oprindeligt forfølger Canada Goose Sne Mantra Parka perfekt læder jakke er et risikabelt.Lytte til hvad jeg sagde ja, bryde fjendens rækker.Men hvis Canada Goose Expedition Parka du har brug for til at føre et mærke, så skal de ikke-it--beidafu.Farver op beidafupi jacket i filmindustrien Canada Goose Yorkville parka, såsom the Dark Knight, x-mænd, og underverdenen.

jayendra's picture
jayendra (visitor) - Mon, 28/11/2011 - 15:23:

Hi,

This is a very good article.
I am new babie in magento so could you provide the complete article for creating module using mvc in magento. That Will be helpful.

Thanks in advance.

Office 2007's picture
Office 2007 (visitor) - Fri, 02/12/2011 - 06:23:

I will keep your new article. I really enjoyed reading this post, thanks for sharing.

gianmarco lorenzi's picture
gianmarco lorenzi (visitor) - Wed, 07/12/2011 - 10:32:

gianmarco lorenzi shop sales the full range of shose.Whether gianmarco lorenzi boots or gianmarco lorenzi pumps,you can see here.Even if you want to buy gianmarco lorenzi sandals in winter is also possible.

ASKWHYWEB Solutions's picture
ASKWHYWEB Solutions (visitor) - Wed, 14/12/2011 - 09:55:

Extremely beautiful article. I would say that I got much more information than before where I was in weak here. Your clear wording gave me an opportunity to overcome these weak points.
Thanks

soldes lancel's picture
soldes lancel (visitor) - Wed, 11/01/2012 - 11:07:

 Évidemment, aucune femme ne peut résister à la tentation de sac lanceles hiver 2012" href="http://www.ventepriveelancel.com/solde-lancel">soldes hiver 2012 la mode. Elles peuvent attendre près d'un an afin d'obtenir une édition limitée de sacs Lancel, surtout le cuir pour les femmes. C'est pourquoi les journalistes toujours attention sur les lancel vente privée sacs commence ». Ils peuvent décrire comment cher et élégant, il est, ce qui signifie son propriétaire a le goût des sacs Lancel haute, il semble que nous pouvons savoir si elle est populaire ou non par son boutique lancel. Sacs Lancel peut être tenue par les mains, le dos, aux poignets et des épaules, de bb lancel pas cher sorte qu'ils se connectent presque chaque partie de femmes. Les sacs sont les meilleurs amis des femmes car elles donnent aux femmes Lancel sentiment inexplicable de sac lancel la sécurité du sens visuel au sens tactile, même une sorte de soupçon psychologiques profondes. Il est le petit champ pour les femmes et contient beaucoup de soldes lancel secrets. Nous pouvons connaître le tempérament rugueux d'une femme en regardant les objets dans son sac Lancel. 

http://www.ventepriveelancel.com/

Anonyme's picture
Anonyme (visitor) - Wed, 11/01/2012 - 21:09:

происхождение фамилии наумов значение моей фамилии значение фамилии гаврилов
значение фамилии бесплатно| значение фамилии соболевская ридель значение фамилии

Anonyme's picture
Anonyme (visitor) - Sun, 15/01/2012 - 22:50:

происхождение фамилии сахарова что означает фамилия глебова значение фамилии гребнев
происхождение фамилии значение фамилии леус значение фамилии костин

ScotWetherington's picture
ScotWetherington (visitor) - Wed, 25/01/2012 - 11:50:

Good and attractive information I take from it..Thank you for posting such a nice article.
Scot

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <p> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options