索引表模式 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 网站上。

上一篇 下一篇
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 查看所有版本


暂无话题~