Magento 中的 Areas

Magento 中的 Areas

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

相关文章
相关标签/搜索