实体属性值模式 Entity Attribute Value Pattern

未匹配的标注

定义

  实体属性值模型是一种用数据模型描述实体的属性和参数,简称EAV模式,属于结构型模式。

一句话概括设计模式

数据由多个实体组成,实体由属性和值组成。

结构中包含的角色

  1. Attribute 属性对象
  2. Value 值对象
  3. Entity 实体对象

最小可表达代码

// 属性对象
class Attribute
{
    private $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}
// 值对象
class Value
{
    private $name;
    private $attribute;

    public function __construct(string $name, Attribute $attribute)
    {
        $this->name = $name;
        $this->attribute = $attribute;
    }

    public function getContent()
    {
        return [
            'name' => $this->name,
            'attribute' => $this->attribute->getName(),
        ];
    }
}
// 实体对象
class Entity
{
    protected $name;
    protected $values = [];

    public function __construct(string $name, array $values)
    {
        $this->name = $name;

        $this->values = $values;
    }

    public function getContent()
    {
        $closure = function ($value) {
                        return $value->getContent();
                    };
        return [
            'name' => $this->name,
            'values' => array_map($closure, $this->values),
        ];
    }
}
// 打印测试信息
$colorAttribute = new Attribute('color');
$colorSilver = new Value('silver', $colorAttribute);
$colorBlack = new Value('black', $colorAttribute);
$memoryAttribute = new Attribute('memory');
$memory8Gb = new Value('8GB', $memoryAttribute);
$entity = new Entity('MacBook Pro', [$colorSilver, $colorBlack, $memory8Gb]);
var_dump(json_encode($entity->getContent()));

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

上一篇 下一篇
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~