本文讨论如何创建一个索引器(Indexer)重建索引(Reindex)。Magento 2 索引中最主要的是索引器。为了代码演示我们继续使用 HelloWorld 模块。
Magento 系统使用索引来变换数据如产品、分类等进而提高店铺的性能。当数据变化时,变换的数据也必须同步更新或重建索引。Magento 使用非常精致的架构在很多数据表中存储大量的店铺数据(包括产品、价格、用户、店铺等数据)。为了优化店铺性能,Magento 使用索引器把累积的数据存储到特定数据表。
比如,你将一个产品的价格从¥8.99改到¥6.99,这时要让前台页面正常显示 Magento 就必须重建价格索引。
如果不使用索引,Magneto就必须实时计算每一个产品的价格——要计算的有客户购物车产品规则、批量价、折扣价、阶梯价等。这样产品的价格计算会花费很长时间,长时间的等待造成的结果可能就是消费者放弃购物。
创建自定义索引器步骤:
- 1 添加索引器配置文件
- 2 添加 Mview 配置文件
- 3 定义索引器类
- 4 运行测试
添加索引器配置文件
文件: app/code/Aqrun/HelloWorld/etc/indexer.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Indexer/etc/indexer.xsd">
<indexer id="aqrun_helloworld_indexer"
view_id="aqrun_helloworld_indexer"
class="Aqrun\HelloWorld\Model\Indexer\Test"
>
<title translate="true">Aqrun HelloWorld Indexer</title>
<description translate="true">你好世界自定义索引器</description>
</indexer>
</config>
上面代码中我们使用 indexer 节点定义了一个新的索引器:
- id 属性是索引器的唯一标识。可以在命令行使用这个ID来检查状态、模式或重建对应的索引
- view_id 是视图元素的ID,视图元素会在 mview 配置文件中进行定义
- class 属性指定我们要处理索引方法的类名
简单的索引还有两个子节点:
- title 节点是显示在索引器列表中的文字
- description 节点索引器列表中的说明文字
添加 Mview 配置文件
mview.xml 文件是用于跟踪指定的实体在数据库中的变化,并运行指定的方法处理这些变化
文件: app/code/Aqrun/HelloWorld/etc/mview.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Mview/etc/mview.xsd">
<view id="aqrun_helloworld_indexer"
class="Aqrun\HelloWorld\Model\Indexer\Test"
group="indexer" >
<subscriptions>
<table name="catalog_product_entity" entity_column="entity_id"/>
</subscription>
</view>
</config>
代码中定义了有ID属性的 view 节点,ID属性关联索引器,class 属性指定了实现有 execute()
方法的类。这个方法会在订阅的数据表有更新时执行。
定义数据表需要用到表名和表的字段,这些参数也会传给 execute()
方法。本例我们指定的表是 catalog_product_entity
。因此无论何时不管是一个还是多个产品被保存,都会执行 Aqrun\HelloWorld\Model\Indexer\Test 类的 execute() 方法。
定义索引器类
根据上面的 indexer.xml 和 mview.xml 配置文件,定义索引器为: Aqrun\HelloWorld\Model\Indexer\Test
文件: app/code/Aqrun/HelloWrold/Model/Indexer/Test.php
<?php
namespace Aqrun\HelloWorld\Model\Indexer;
class Test implements \Magento\Framework\Indexer\ActionInterface,
\Magento\Framework\Mview\ActionInterface
{
/**
* 被 mview 调用,允许在 "Update on schedule" 模式下处理索引
* @param int[] $ids
*/
public function execute($ids){
//code
}
/**
* 会处理所有的数据并重建索引
* 在使用命令行重建索引时会执行
*/
public function executeFull(){
//code
}
/**
* 作用于一组实体的变化(如批量操作)
* @param array $ids
*/
public function executeList(array $ids){
//code
}
/**
* 作用于单个实体
* @param int $id
*/
public function executeRow($id){
// code
}
}
你可以在索引器类方法中添加代码向索引器表更新数据
接下来,清空缓存并到后台菜单 system > Index Management 查看代码结果
重建索引使用命令:
php bin/magento indexer:redinex