-
Sometimes we need to overwrite an observer. The first way that usually comes in mind is overwriting the model. Usually is named Observer.php, because this is the “best practice”.
And NO, you don’t have to overwrite the model. Observer.php doesn’t extend anything anyway and usually contains all of the module’s observers, so you can’t overwrite the same observer in more than one module.
How it works?
In magento when a new observer is added, it must have an unique identifier. This identifier is the key!Actually, there is another element: “area”. When Mage::dispatchEvent(…) is performed, events will be dispatched using “area” and “identifier”.
For example, the admin notification system, which is observing “controller_action_predispatch”, will run:
1=> "global"(area) 2=> "controller_action_predispatch"(event) 3=> "adminnotification"(identifier)
then:
1=> "adminhtml"(area) 2=> "controller_action_predispatch"(event) 3=> "adminnotification"(identifier)
If the event was in the frontend area, it would be: “global” then “frontend”.
Overwriting
Overwriting is in fact a observer defined in the same config area as the original event (global, frontend or adminhtml), attached to the same event and with the same identifier as the original observer (e.g. adminnotification).Let’s say we have to overwrite “adminnotification”. This observer is in Mage/AdminNotification. The unique identifier is defined in etc/config.xml:
1... 2 <adminhtml> 3... 4 <events> 5 <controller_action_predispatch> 6 <observers> 7 <adminnotification> 8 <class>adminnotification/observer</class> 9 <method>preDispatch</method> 10 </adminnotification> 11 </observers> 12 </controller_action_predispatch> 13 </events> 14... 15 </adminhtml> 16...
From the example above we can see:
– area: adminhtml
– event: controller_action_predispatch
– identifier: adminnotificationThe module activation file will be: app/etc/modules/CP_AdminNotification.xml
1<?xml version="1.0"?> 2<config> 3 <modules> 4 <CP_AdminNotification> 5 <active>true</active> 6 <codePool>local</codePool> 7 <depends> 8 <Mage_AdminNotification/> 9 </depends> 10 </CP_AdminNotification> 11 </modules> 12</config>
I’ve added dependencies because without the original module, this module will be useless.
There’s a “best practice” to name a module that is overwritten with the same name as the original module.
The configuration file for this module, will contain practically everything you’ll need for the overwriting: area, event and identifier. The file is located in app/code/local/CP/AdminNotification/etc/config.xml:
1<?xml version="1.0"?> 2<config> 3 <modules> 4 <CP_AdminNotification> 5 <version>0.0.1</version> 6 </CP_AdminNotification> 7 </modules> 8 <global> 9 <models> 10 <cp_adminnotification> 11 <class>CP_AdminNotification_Model</class> 12 </cp_adminnotification> 13 </models> 14 </global> 15 <adminhtml> 16 <events> 17 <controller_action_predispatch> 18 <observers> 19 <adminnotification> 20 <class>cp_adminnotification/observer</class> 21 <method>overwrittenPreDispatch</method> 22 </adminnotification> 23 </observers> 24 </controller_action_predispatch> 25 </events> 26 </adminhtml> 27</config>
The observer should contain all the new logic. The file is in app/code/local/CP/AdminNotification/Model/Observer.php, just like you would probably expect from the structure above.
1<?php 2 3class CP_AdminNotification_Model_Observer { 4 5 public function overwrittenPreDispatch(Varien_Event_Observer $observer) { 6 // noua logica din observer 7 } 8}
Disabling
Disabling is preaty similar to overwriting, the difference is in the config and the fact that an observer file is not needed anymore, because there isn’t a new logic.The new config.xml file is:
1<?xml version="1.0"?> 2<config> 3... 4 <adminhtml> 5 <events> 6 <controller_action_predispatch> 7 <observers> 8 <adminnotification> 9 <type>disabled</type> 10 </adminnotification> 11 </observers> 12 </controller_action_predispatch> 13 </events> 14 </adminhtml> 15</config>
-
This is not a tutorial about setting up a Shopping Cart Price Rule in Magento, but rather about implementing a new one.
A new type of rule in Magento needs a couple of things:
– modify the admin area to add the new rule using an observer for adminhtml_block_salesrule_actions_prepareform,
– a way to apply the new rule using an observer for salesrule_validator_process.Let’s build an example. Let’s say there is a Shopping Cart Price Rule that offers different discounts according to the number of products in the cart. The value that’s going to be used for the discount increment ($step) will be calculated. The first product will not receive a discount, the second product will receive a discount of $step, the third product will have a discount of 2*$step, until the maximum discount value will be reached. The following products will have a maximum discount. Ex:
Discount Amount = 50
Discount Qty = 5
Step = Discount Amount / Discount Qty = 10Discount outcome:
– 0% prod 1
– 10% prod 2
…
– 50% prod 6
– 50% prod 7The first step is the module activation using the file: app/etc/modules/CP_ProductNrDiscount.xml
1<?xml version="1.0" encoding="UTF-8"?> 2<config> 3 <modules> 4 <CP_ProductNrDiscount> 5 <active>true</active> 6 <codePool>local</codePool> 7 </CP_ProductNrDiscount> 8 </modules> 9</config>
The first observer, adminhtml_block_salesrule_actions_prepareform, must be in the “adminhtml” section of the config, because it will involve the admin. This observer will have access to the admin form, in order to modify it.
The second observer, salesrule_validator_process, can be in the “frontend” or “global” section of the config. If it’s in the frontend section, it will only apply to the frontend section. If it’s in the global section it will also apply to backend. Usually, global is necessary when there are actions on the cart in the backend.
1<?xml version="1.0" encoding="UTF-8"?> 2<config> 3 <modules> 4 <CP_ProductNrDiscount> 5 <version>0.0.1</version> 6 </CP_ProductNrDiscount> 7 </modules> 8 <global> 9 <models> 10 <productnrdiscount> 11 <class>CP_ProductNrDiscount_Model</class> 12 </productnrdiscount> 13 </models> 14 <events> 15 <salesrule_validator_process> 16 <observers> 17 <productnrdiscount> 18 <type>model</type> 19 <class>productnrdiscount/observer</class> 20 <method>salesruleValidatorProcess</method> 21 </productnrdiscount> 22 </observers> 23 </salesrule_validator_process> 24 </events> 25 </global> 26 <adminhtml> 27 <events> 28 <adminhtml_block_salesrule_actions_prepareform> 29 <observers> 30 <productnrdiscount> 31 <type>model</type> 32 <class>productnrdiscount/observer</class> 33 <method>adminhtmlBlockSalesruleActionsPrepareform</method> 34 </productnrdiscount> 35 </observers> 36 </adminhtml_block_salesrule_actions_prepareform> 37 </events> 38 </adminhtml> 39</config>
As you can see above, there must be an Observer model that will have the two methods which modify the admin and apply the discount.
1<?php 2/** 3 * Number of product discount module 4 * 5 * @author Claudiu Persoiu https://blog.claudiupersoiu.ro 6 */ 7class CP_ProductNrDiscount_Model_Observer { 8 9 // The new rule type 10 const PRODUCT_NR_DISCOUNT = 'product_nr_discount'; 11 12 /** 13 * Add the new rule type to the admin menu 14 * 15 * @param Varien_Event_Observer $observer 16 */ 17 public function adminhtmlBlockSalesruleActionsPrepareform 18 (Varien_Event_Observer $observer) { 19 // Extract the form field 20 $field = $observer->getForm()->getElement('simple_action'); 21 // Extract the field values 22 $options = $field->getValues(); 23 // Add the new value 24 $options[] = array( 25 'value' => self::PRODUCT_NR_DISCOUNT, 26 'label' => 'Product Number Discount' 27 ); 28 // Set the field 29 $field->setValues($options); 30 } 31 32 /** 33 * Apply the discount 34 * The discount will be applied for at least 2 products increasing 35 * with a "step" for each product, where "step" is 36 * maximum discount / number of products. 37 * 38 * @param Varien_Event_Observer $observer 39 */ 40 public function salesruleValidatorProcess(Varien_Event_Observer $observer) { 41 42 // $item typeof Mage_Sales_Model_Quote_Item 43 $item = $observer->getEvent()->getItem(); 44 // $rule typeof Mage_SalesRule_Model_Rule 45 $rule = $observer->getEvent()->getRule(); 46 47 // Number of products 48 $qty = $item->getQty(); 49 50 // We must check the rule type in order to isolate our rule type 51 if($rule->getSimpleAction() == self::PRODUCT_NR_DISCOUNT && $qty > 1) { 52 53 // Extract rule details 54 $discountAmount = $rule->getDiscountAmount(); 55 $discountQty = $rule->getDiscountQty(); 56 57 // Discount step 58 $step = $discountAmount/$discountQty; 59 60 // Discount calculation 61 $discount = 0; 62 for($i = 1; $i < $qty; $i++) { 63 $itemDiscount = $i * $step; 64 // If the discount is bigger then the maximum discount 65 // then the maximum discount is used 66 if($itemDiscount > $discountAmount) { 67 $itemDiscount = $discountAmount; 68 } 69 70 $discount += $itemDiscount; 71 } 72 // Effective discount 73 $totalDiscountAmount = ($item->getPrice() * $discount)/100; 74 75 // Discount in percent for each item 76 $item->setDiscountPercent($discount / $qty); 77 78 // Setting up the effective discount, basically this is the discount value 79 $result = $observer->getResult(); 80 $result->setDiscountAmount($totalDiscountAmount); 81 $result->setBaseDiscountAmount($totalDiscountAmount); 82 83 } 84 } 85 86}
This observer will run at each request if there are items in cart that for which the rule is applicable. If the discount should be applied only for specific products, there can be filtered using the rule’s “Conditions” tab, just as you would normally do.
-
Observer pattern refers to a class called “subject” that has a list of dependents, called observers, and notifies them automatically each time an action is taking place.
A small example of why is used:
– let’s say we have a class with does someting:
1class Actiune { 2 private $val; 3 function __construrct() { 4 // someting in the constructor 5 } 6 7 function change($val) { 8 $this->val = $val; 9 } 10}
Each time $val changes we want to call a method of an “observer” object:
1class Actiune { 2 private $val; 3 function __construrct() { 4 // someting in the constructor 5 } 6 7 function change($val, $observator) { 8 $this->val = $val; 9 $observator->update($this); 10 } 11}
Theoretically is not bad, but the more methods there are so does the dependence grows bigger and each time we add a new observer object we must modify the class, with will probably result in chaos, which will be almost impossible to port.
Now, the observator pattern looks something like this:
SPL (Standard PHP Library), which is well known for it’s defined iterators, comes with the interfaces SplSubject and SplObserver, for the subject and respectively the observer.
An implementation looks someting like this:
1/** 2 * the class which must be monitored 3 */ 4class Actiune implements SplSubject { 5 private $observatori = array(); 6 private $val; 7 8 /** 9 * method to attach an observer 10 * 11 * @param SplObserver $observator 12 */ 13 function attach(SplObserver $observator) { 14 $this->observatori[] = $observator; 15 } 16 17 /** 18 * method to detach an observer 19 * 20 * @param SplObserver $observator 21 */ 22 function detach(SplObserver $observator) { 23 $observatori = array(); 24 foreach($this->observatori as $observatorul) { 25 if($observatorul != $observator) $observatori[] = $observatorul; 26 } 27 $this->observatori = $observatori; 28 } 29 30 /** 31 * method that notifies the observer objects 32 */ 33 function notify() { 34 foreach($this->observatori as $observator) { 35 $observator->update($this); 36 } 37 } 38 39 /** 40 * method for makeing changes in the class 41 * 42 * @param int $val 43 */ 44 function update($val) { 45 echo 'updateing...'; 46 $this->val = $val; 47 $this->notify(); 48 } 49 50 /** 51 * public method with the subject's status 52 * 53 * @return int 54 */ 55 function getStatus() { 56 return $this->val; 57 } 58} 59 60/** 61 * and observer class 62 */ 63class Observator implements SplObserver { 64 function update(SplSubject $subiect) { 65 echo $subiect->getStatus(); 66 } 67} 68 69// an observer instance 70$observator = new Observator(); 71 72// an subject instance 73$subiect = new Actiune(); 74 75// attaching an observer to the subject 76$subiect->attach($observator); 77 78// update subject 79$subiect->update(5);
What seems strange is that there isn’t any documentation on this SPL interfaces. Even on the Zend website there is an article PHP Patterns: The Observer Pattern which does not use SPL, but for something like namespaces there was documentation even before PHP 5.3 was out.