Magento 中的 Areas
area 是一个逻辑组件,用来组织申请解决相干的代码。针对 area, 咱们绝大部分时候不须要做非凡解决,然而了解 area 对于了解 Magento 相当重要。
在 MagentoFrameworkAppArea 类中的 AREA_* 相干常量暗示了 area 的品种。大抵有以下几种:
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 参数中
- 位于 <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。
看看 <MAGENTO_DIR>/module-webapi/etc/di.xml 文件中的例子。
<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 下的特定代码。
开发一个模块的时,咱们可能定义在特定的 area 中那些资源是可见的或者可拜访的。通过这种形式来管制特定 area 中的行为表现。对应的例子是咱们可能在 frontend area 中定义 customer_save_after event 对应的观察者。对应的观察者只能在保留用户数据的时候被触发,而且只能在店铺前台触发,通常是在用户注册时。adminhtml area 中的相干操作,比方在 Magento 后盾手动创立用户并不能触发对应的监听者,因为对应的监听者是注册在 frontend area 中的。
有时,咱们想要在特定的 area 中运行代码,这种状况下, MagentoStoreModelAppEmulation 类提供了startEnvironmentEmulation
和 stopEnvironmentEmulation办法可能帮忙咱们实现对应的性能,具体的例子如下:
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定义即可,不过这种形式并不常见。
原文链接:http://kaijuan.co/topics/51/t...