Magento 2中,索引器是一个关键的功能,用于提高在线商店的性能和响应速度。索引器有助于转换产品、类别和其他数据,以确保商店的顺畅运行。本文将介绍如何在Magento 2中创建和配置索引器,并通过示例模块(Example_HelloWorld)演示如何重新索引商店。

10.jpg

1、什么是索引器?

索引器是Magento 2中的重要功能,用于提高商店性能。当商店中的数据发生更改时,例如产品价格的变化,Magento必须重新计算和更新这些数据。索引器的任务是将这些数据转换并存储在特殊的表中,以加快商店的响应速度。

2、创建索引器的步骤。

要创建和配置自定义索引器,需要按照以下步骤操作:

步骤 1:创建索引器配置文件。

首先,需要创建一个索引器配置文件(indexer.xml)。此文件将定义索引器的基本信息,包括其标识符、视图ID和处理索引的类。

xml

Copy code

<?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="example_helloworld_indexer" view_id="example_helloworld_indexer" class="Example\HelloWorld\Model\Indexer\Test">

        <title translate="true">Example HelloWorld Indexer</title>

        <description translate="true">HelloWorld of custom indexer</description>

    </indexer>

</config>

在此配置文件中,我们定义了一个名为"example_helloworld_indexer"的索引器,指定了处理索引的类为"Example\HelloWorld\Model\Indexer\Test"

步骤 2:创建Mview配置文件。

Mview配置文件(mview.xml)用于跟踪数据库表的更改并运行相应的处理程序。在该文件中,需要定义视图元素,指定要监视的表和执行索引的类。

xml

Copy code

<?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="example_helloworld_indexer" class="Example\HelloWorld\Model\Indexer\Test" group="indexer">

        <subscriptions>

            <table name="catalog_product_entity" entity_column="entity_id" />

        </subscriptions>

    </view>

</config>

在上述示例中,我们定义了一个名为"example_helloworld_indexer"的视图,指定了要监视的表为"catalog_product_entity"。这意味着每当该表中的数据发生更改时,将运行我们在类"Example\HelloWorld\Model\Indexer\Test"中定义的执行方法。

步骤 3:创建索引器类。

现在,让我们创建索引器的实际类,该类将处理索引操作。在我们的示例中,类名为"Example\HelloWorld\Model\Indexer\Test"

php

Copy code

<?php

namespace Example\HelloWorld\Model\Indexer;

class Test implements \Magento\Framework\Indexer\ActionInterface, \Magento\Framework\Mview\ActionInterface

{

/*

* Used by mview, allows process indexer in the "Update on schedule" mode

*/

public function execute($ids){

// 在此处编写代码以处理索引

}

 

/*

* Will take all of the data and reindex

* Will run when reindex via command line

*/

public function executeFull(){

// 在此处编写代码以处理完整的重新索引

}

   

/*

* Works with a set of entity changed (may be massaction)

*/

public function executeList(array $ids){

// 在此处编写代码以处理一组实体的更改

}

   

/*

* Works in runtime for a single entity using plugins

*/

public function executeRow($id){

// 在此处编写代码以处理单个实体的更改

}

}

在上述类中,我们实现了不同的执行方法,用于处理不同类型的索引操作。可以根据需求编写代码来处理索引。

步骤 4:运行测试。

完成以上步骤后,可以通过命令行运行重新索引以查看结果:

bash

Copy code

php bin/magento indexer:reindex

这将触发创建的索引器执行相应的索引操作。

结论:

Magento 2的索引器是优化和提高商店性能的关键工具。通过创建自定义索引器,可以控制数据的转换和存储,以确保商店始终保持高性能。遵循上述步骤,可以轻松创建和配置自定义索引器,并通过重新索引来更新商店数据。

(本文内容根据网络资料整理,出于传递更多信息之目的,不代表连连国际赞同其观点和立场。)