Magento事件机制 - Magento Event/Observer
生活随笔
收集整理的這篇文章主要介紹了
Magento事件机制 - Magento Event/Observer
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
為了擴展Magento的功能,我們可以重寫Magento的代碼,但因為代碼只能被重寫一次,所以當多個模塊需要重寫同一部分的代碼時,就會引起沖突,好在Magento提供了另一種擴展功能的方法:事件機制,原理是在需要擴展的地方觸發(fā)事件,各模塊捕捉到事件后,如果有該事件的響應(yīng),便執(zhí)行對應(yīng)的代碼,這樣便實現(xiàn)了在多個模塊中擴展程序的功能。 我們首先看一下Magento系統(tǒng)中預(yù)定義了哪些事件:Magento Events?, 這個表格有三列,第一列是事件的名稱,比如"customer_login",我們大概知道,這是用戶登錄時觸發(fā)的事件;第二列是事件的作用域,只要有g(shù)lobal/frontend/adminhtml這三種,分別是全局/前臺/后臺作用域,我們可以指定在哪些作用域響應(yīng)該事件;最后一列是相應(yīng)該事件的模塊,比如"customer_login"事件在Catalog,Checkout,Log,Reports,Wishlist這幾個模塊中都有相應(yīng)。ba 如果需要找到觸發(fā)事件的地方,可以在《Magento Event/Observer Hooks Cheat Sheet》這個網(wǎng)頁中搜索,比如通過查找,我們可以知道"customer_login"這個事件是在 app/code/core/Mage/Customer/Model/Session.php 這個文件中觸發(fā)的,我們打開這個文件,會發(fā)現(xiàn)這樣的代碼: class Mage_Customer_Model_Session extends Mage_Core_Model_Session_Abstract
{// ...public function setCustomerAsLoggedIn($customer){$this->setCustomer($customer);Mage::dispatchEvent('customer_login', array('customer'=>$customer));return $this;}
} 我們可以發(fā)現(xiàn)"customer_login"事件是在Mage_Customer_Model_Session類的setCustomerAsLoggedIn()函數(shù)中通過Mage::dispatchEvent()觸發(fā)的,同時把customer變量作為參數(shù)傳遞給相應(yīng)事件的對象。 我們再來分析模塊是怎樣相應(yīng)事件的,仍以"customer_login"這個事件為例,我們看到Log模塊響應(yīng)了該事件,打開/app/code/core/Mage/Log/etc/config.xml文件,會看到這樣的部分代碼: <config><frontend><events><customer_login><observers><log><class>log/visitor</class><method>bindCustomerLogin</method></log></observers></customer_login></events></frontend>
<config>
可以看到在Log模塊中是在前臺相應(yīng)"customer_login"事件的,捕捉到這個事件時將執(zhí)行"log/visitor"類的"bindCustomerLogin"方法,我們打開/app/code/core/Mage/Log/Model/Visitor.php文件,將發(fā)現(xiàn)這樣的代碼:
class Mage_Log_Model_Visitor extends Mage_Core_Model_Abstract {// ...public function bindCustomerLogin($observer){if (!$this->getCustomerId() && $customer = $observer->getEvent()->getCustomer()) {$this->setDoCustomerLogin(true);$this->setCustomerId($customer->getId());}return $this;} }在觸發(fā)事件時我們使用 Mage::dispatchEvent('customer_login', array('customer'=>$customer)); 的第二個參數(shù)傳遞變量,在bindCustomerLogin($observer)函數(shù)中使用$observer參數(shù)獲取該變量$customer = $observer->getEvent()->getCustomer(),之后進行相應(yīng)的擴展。
轉(zhuǎn)載于:https://www.cnblogs.com/zhengyanbin2016/p/6029127.html
新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產(chǎn)品紅包拿不停!總結(jié)
以上是生活随笔為你收集整理的Magento事件机制 - Magento Event/Observer的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js+dom开发第十六天
- 下一篇: virtualbox+oracle li