4.3. Entity-Attribute-Value (EAV)
The Entity–attribute–value (EAV) pattern in order to implement EAV model with PHP.
4.3.1. Purpose
The Entity–attribute–value (EAV) model is a data model to describe entitieswhere the number of attributes (properties, parameters) that can be usedto describe them is potentially vast, but the number that will actually applyto a given entity is relatively modest.
4.3.2. UML Diagram
4.3.3. Code
You can also find this code on GitHub
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
- <?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);
- }
- }
4.3.4. Test
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);
- }
- }