索引表模式 Index Table Pattern

未匹配的标注

描述#

能让应用程序快速地定位数据,提高查询的性能。

背景和问题#

应用程序可能不能够使用主键而是需要使用其他字段来检索数据。

解决方案#

数据存储不支持二级索引,可以通过创建自己的索引表手动效仿他们。

注意事项#

  1. 保证辅助索引的性能开销。
  2. 维持索引表和原始数据之间的一致性。有可能设计围绕最终一致性模型的应用。

何时使用#

应用程序需要使用主键之外的字段检索数据。

结构中包含的角色#

  1. Storage 数据仓库
  2. Application 应用程序
  3. IndexTable 索引表

可用到的设计模式思维#

应用程序把数据的索引生成给了索引表,两个对象协同处理同一个请求,符合委托模式。

最小可表达代码#

// 数据仓库
class Storage
{
    public static function getTestData()
    {
        return [
            ['id' => 1, 'name' => '张3', 'age' => 18],
            ['id' => 2, 'name' => '张4', 'age' => 18],
            ['id' => 3, 'name' => '张5', 'age' => 20],
        ];
    }
}

// 应用程序
class Application
{
    protected $indexTable;

    public function __construct()
    {
        $data = Storage::getTestData();

        $this->indexTable = new IndexTable($data);
    }

    public function getDataByAge(int $age) : array
    {
        return $this->indexTable->getDataByAge($age);
    }
}

// 索引表
class IndexTable
{
    protected $data = [];
    protected $ageIndexData = [];

    public function __construct(array $data)
    {
        $this->data = $data;

        $this->makeToAgeTable();
    }

    public function getDataByAge(int $age) : array
    {
        return $this->ageIndexData[$age] ?? [];
    }

    protected function makeToAgeTable()
    {
        foreach ($this->data as $value) {
            $this->ageIndexData[$value['age']][] = $value;
        }
    }
}

$data = (new Application)->getDataByAge(55);
var_dump($data);

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~