物體屬性值(Entity--attribute--value EAV)模式,可以方便 PHP 實作 EAV 模型,
目的
物體屬性值模型(Entity-attribute-value EAV)是一種用資料模型描述物體的屬性(屬性,引數),可以用來形容他們潛在巨大,但實際上將適用于給定的物體的數量是相對較少,
在數學中,這種模式被稱為一個稀疏矩陣 ,
EAV 也被稱為物件的屬性值的模式,垂直的資料庫模型和開放式架構,
UML圖

★官方PHP高級學習交流社群「點擊」管理整理了一些資料,BAT等一線大廠進階知識體系備好(相關學習資料以及筆面試題)以及不限于:分布式架構、高可擴展、高性能、高并發、服務器性能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell腳本、Docker、微服務、Nginx等多個知識點高級進階干貨
代碼
- Entity.php
<?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);
}
}
- Attribute.php
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;
}
}
- Value.php
<?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);
}
}
測驗
- Tests/EAVTest.php
<?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 互聯網架構師成長之路*「設計模式」終極指南
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)
面試10家公司,識訓9個offer,2020年PHP 面試問題
★如果喜歡我的文章,想與更多資深開發者一起交流學習的話,獲取更多大廠面試相關技術咨詢和指導,歡迎加入我們的群啊,暗號:phpzh
2020年最新PHP進階教程,全系列!

內容不錯的話希望大家支持鼓勵下點個贊/喜歡,歡迎一起來交流;另外如果有什么問題 建議 想看的內容可以在評論提出
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/106315.html
標籤:其他
