EAV 實體屬性值模式(多用於數據庫)

<?php

/**
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永無BUG
 *
 * php 技術羣:781742505
 *
 * Class Entity
 */
class Entity
{
    /**
     * @var
     */
    protected $name;
    /**
     * @var array
     */
    protected $attribute = [];

    /**
     * Entity constructor.
     *
     * @param $name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * @param Attribute $attribute
     */
    public function setAttribute(Attribute $attribute)
    {
        $this->attribute[] = $attribute;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        $return = $this->name."\n";
        foreach ($this->attribute as $attribute) {
            $return .= '  '.$attribute->name.' => '.$attribute->value."\n";
        }

        return $return;
    }

}

/**
 * Class Attribute
 */
class Attribute
{
    /**
     * @var
     */
    public $name;

    /**
     * @var null
     */
    public $value;

    /**
     * Attribute constructor.
     *
     * @param      $name
     * @param null $value
     */
    public function __construct($name, $value = null)
    {
        $this->name = $name;
        $this->value = $value;
    }
}

/**
 * Class Value
 */
class Value
{
    /**
     * @var
     */
    public $value;

    /**
     * Value constructor.
     *
     * @param Attribute $attribute
     * @param           $value
     */
    public function __construct(Attribute $attribute, $value)
    {
        $attribute->value = $value;
    }
}

$entity = new Entity('汽車');
$attribute1 = new Attribute('顏色');
$attribute2 = new Attribute('價格');
$entity->setAttribute($attribute1);
$entity->setAttribute($attribute2);

new Value($attribute1, 'red');
new Value($attribute2, '20 萬元');

echo $entity;

// 汽車
//   顏色 => red
//   價格 => 20 萬元

// 這個例子實現的不好,因爲它必須新建一個屬性再綁定屬性值。
// 而理論應該是屬性應當可以複用。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章