索引表模式 Index Table Pattern
描述#
能让应用程序快速地定位数据,提高查询的性能。
背景和问题#
应用程序可能不能够使用主键而是需要使用其他字段来检索数据。
解决方案#
数据存储不支持二级索引,可以通过创建自己的索引表手动效仿他们。
注意事项#
- 保证辅助索引的性能开销。
- 维持索引表和原始数据之间的一致性。有可能设计围绕最终一致性模型的应用。
何时使用#
应用程序需要使用主键之外的字段检索数据。
结构中包含的角色#
- Storage 数据仓库
- Application 应用程序
- 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);
推荐文章: