實體屬性值(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架構
內容不錯的話但願你們支持鼓勵下點個贊/喜歡,歡迎一塊兒來交流;另外若是有什麼問題 建議 想看的內容能夠在評論提出