I have been reading a couple of tutorials and am now trying to create my own observer.
The way I understand observers, is that when you observe an event a parameter will be automatically passed to it, but how do I know what is being passed?
I thought the below example would pass Mage_Catalog_Model_Product
as a parameter. But when I try to implement this in my code I get the following error
..._Model_Observer::_generateDiscount() must be an instance of Mage_Catalog_Model_Product
(I have added my code below)
I'm trying to use the dispatchEvent() in getFinalPrice()
Mage_Catalog_Model_Product_Type_Price.php
/**
* Retrieve product final price
*
* @param float|null $qty
* @param Mage_Catalog_Model_Product $product
* @return float
*/
public function getFinalPrice($qty = null, $product)
{
if (is_null($qty) && !is_null($product->getCalculatedFinalPrice())) {
return $product->getCalculatedFinalPrice();
}
$finalPrice = $this->getBasePrice($product, $qty);
$product->setFinalPrice($finalPrice);
Mage::dispatchEvent('catalog_product_get_final_price', array('product' => $product, 'qty' => $qty));
$finalPrice = $product->getData('final_price');
$finalPrice = $this->_applyOptionsPrice($product, $qty, $finalPrice);
$finalPrice = max(0, $finalPrice);
$product->setFinalPrice($finalPrice);
return $finalPrice;
}
My observer
class Mdeprojects_Discount_Model_Observer
{
public function applyDiscount()
{
$this->_generateDiscount();
}
protected function _generateDiscount(Mage_Catalog_Model_Product $product)
{
$discount = $product->getFinalPrice() / 100 * 50;
return $discount;
}
}
I have also tried
protected function _generateDiscount(Varien_Event_Observer $product)
{
$discount = $product->_data['final_price'] / 100 * 50;
return $discount;
}
I am misunderstanding how observers work could someone please point out where my error(s) is/are?
Best Answer
Each observer receives as parameter an instance of
Varien_Event_Observer
that has a member calledevent
that is an instance ofVarien_Event
.You can access this member by calling
$observer->getEvent()
.This
event
contains all the variables passed to the observer and you can get them by usinggetData('obj_key')
orgetObjKey()
, wherenobj_key
is the key passed when the event is dispatched.It sounds more complicated than it is. Let's take your example.
The event dispatched is
This means that your observer should look like this: