area 是一個邏輯組件,用來組織請求處理相關的代碼。針對 area, 咱們絕大部分時候不須要作特殊處理,可是理解 area 對於理解 Magento 至關重要。
在 MagentoFrameworkAppArea 類中的 AREA_* 相關常量暗示了 area 的種類。大體有如下幾種:php
const AREA_GLOBAL = 'global'; const AREA_FRONTEND = 'frontend'; const AREA_ADMINHTML = 'adminhtml'; const AREA_DOC = 'doc'; const AREA_CRONTAB = 'crontab'; const AREA_WEBAPI_REST = 'webapi_rest'; const AREA_WEBAPI_SOAP = 'webapi_soap';
經過在 <MAGENTO_DIR> di.xml 文件中搜索 <argument name="areas" 字符串,咱們能發現至少有 5 種 area 被添加到了 MagentoFrameworkAppAreaList 類的 areas 參數中html
- 位於 <MAGENTOI_DIR>/module-backend/etc/di.xml 的 adminhtml
- 位於 <MAGENTOI_DIR>/module-webapi/etc/di.xml 的 webapi_rest
- 位於 <MAGENTOI_DIR>/magento/module-webapi/etc/di.xml 的 webapi_soap
- 位於 <MAGENTOI_DIR>/magento/module-store/etc/di.xml 的 frontend
- 位於 <MAGENTOI_DIR>/magento/module-cron/etc/di.xml 的 crontab
默認的 area 是 frontend, 是由 module-store/etc/di.xml 文件中的 default 參數定義的。 global area 是在缺失 adminhtml 和 frontend area 狀況下的默認的 area。web
看看 <MAGENTO_DIR>/module-webapi/etc/di.xml 文件中的例子。api
<type name="Magento\Framework\App\AreaList"> <arguments> <argument name="areas" xsi:type="array"> <item name="webapi_rest" xsi:type="array"> <item name="frontName" xsi:type="string">rest</item> </item> <item name="webapi_soap" xsi:type="array"> <item name="frontName" xsi:type="string">soap</item> </item> </argument> </arguments> </type>
frontName 有時會出如今 URL 中,name 用於在內部引用配置文件中對應的 area, Magento 中定義了不一樣的 area, 裏面包含不一樣的用來處理 URL 和請求的相關代碼。好處是 Magento 只用加載對應 area 下的特定代碼。frontend
開發一個模塊的時,咱們可以定義在特定的 area 中那些資源是可見的或者可訪問的。經過這種方式來控制特定 area 中的行爲表現。對應的例子是咱們可以在 frontend area 中定義 customer_save_after event 對應的觀察者。對應的觀察者只能在保存用戶數據的時候被觸發,並且只能在店鋪前臺觸發,一般是在用戶註冊時。adminhtml area 中的相關操做,好比在 Magento 後臺手動建立用戶並不能觸發對應的監聽者,由於對應的監聽者是註冊在 frontend area 中的。this
有時,咱們想要在特定的 area 中運行代碼,這種狀況下, MagentoStoreModelAppEmulation 類提供了startEnvironmentEmulation
和 stopEnvironmentEmulation方法可以幫助咱們實現對應的功能,具體的例子以下:rest
protected $storeRepository; protected $emulation; public function __construct( \Magento\Store\Api\StoreRepositoryInterface $storeRepository, \Magento\Store\Model\App\Emulation $emulation ) { $this->storeRepository = $storeRepository; $this->emulation = $emulation; } public function test() { $store = $this->storeRepository->get('store-to-emulate'); $this->emulation->startEnvironmentEmulation( $store->getId(), \Magento\Framework\App\Area::AREA_FRONTEND ); // Code to execute in emulated environment $this->emulation->stopEnvironmentEmulation(); }
咱們也可以定義本身的 area, 經過在模塊的 di.xml定義便可,不過這種方式並不常見。code
原文連接:http://kaijuan.co/topics/51/t...xml