实体属性值(Entity--attribute--value EAV)模式,能够方便 PHP 实现 EAV 模型。php
实体属性值模型(Entity-attribute-value EAV)是一种用数据模型描述实体的属性(属性,参数),能够用来形容他们潜在巨大,但实际上将适用于给定的实体的数量是相对较少。laravel
在数学中,这种模式被称为一个稀疏矩阵 。面试
EAV 也被称为对象的属性值的模式,垂直的数据库模型和开放式架构。sql
<?php namespace DesignPatterns\More\EAV; class Entity { /** * @var \SplObjectStorage */ private $values; /** * @var string */ private $name; /** * @param string $name * @param Value[] $values */ public function __construct(string $name, $values) { $this->values = new \SplObjectStorage(); $this->name = $name; foreach ($values as $value) { $this->values->attach($value); } } public function __toString(): string { $text = [$this->name]; foreach ($this->values as $value) { $text[] = (string) $value; } return join(', ', $text); } }
Value.php <?php namespace DesignPatterns\More\EAV; class Attribute { /** * @var \SplObjectStorage */ private $values; /** * @var string */ private $name; public function __construct(string $name) { $this->values = new \SplObjectStorage(); $this->name = $name; } public function addValue(Value $value) { $this->values->attach($value); } /** * @return \SplObjectStorage */ public function getValues(): \SplObjectStorage { return $this->values; } public function __toString(): string { return $this->name; } }
<?php namespace DesignPatterns\More\EAV; class Value { /** * @var Attribute */ private $attribute; /** * @var string */ private $name; public function __construct(Attribute $attribute, string $name) { $this->name = $name; $this->attribute = $attribute; $attribute->addValue($this); } public function __toString(): string { return sprintf('%s: %s', $this->attribute, $this->name); } }
<?php namespace DesignPatterns\More\EAV\Tests; use DesignPatterns\More\EAV\Attribute; use DesignPatterns\More\EAV\Entity; use DesignPatterns\More\EAV\Value; use PHPUnit\Framework\TestCase; class EAVTest extends TestCase { public function testCanAddAttributeToEntity() { $colorAttribute = new Attribute('color'); $colorSilver = new Value($colorAttribute, 'silver'); $colorBlack = new Value($colorAttribute, 'black'); $memoryAttribute = new Attribute('memory'); $memory8Gb = new Value($memoryAttribute, '8GB'); $entity = new Entity('MacBook Pro', [$colorSilver, $colorBlack, $memory8Gb]); $this->assertEquals('MacBook Pro, color: silver, color: black, memory: 8GB', (string) $entity); } }
PHP 互联网架构师 50K 成长指南+行业问题解决总纲(持续更新)设计模式
面试10家公司,收获9个offer,2020年PHP 面试问题服务器
★若是喜欢个人文章,想与更多资深开发者一块儿交流学习的话,获取更多大厂面试相关技术咨询和指导,欢迎加入咱们的群啊,暗号:phpzh架构
内容不错的话但愿你们支持鼓励下点个赞/喜欢,欢迎一块儿来交流;另外若是有什么问题 建议 想看的内容能够在评论提出