实体属性值模式 Entity Attribute Value Pattern
定义
实体属性值模型是一种用数据模型描述实体的属性和参数,简称EAV模式,属于结构型模式。
一句话概括设计模式
数据由多个实体组成,实体由属性和值组成。
结构中包含的角色
- Attribute 属性对象
- Value 值对象
- 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()));
推荐文章: