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