【教程】Magento 中的 Areas

Magento 中的 Areas

area 是一个逻辑组件,用来组织请求处理相关的代码。针对 area, 我们绝大部分时候不需要做特殊处理,但是理解 area 对于理解 Magento 相当重要。 在 Magento\Framework\App\Area 类中的 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 被添加到了 Magento\Framework\App\AreaList 类的 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 中运行代码,这种情况下, Magento\Store\Model\App\Emulation 类提供了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定义即可,不过这种方式并不常见。