Реализован как класс с примесью.
Примесь - основной функционал, а класс дополнительный методы.
Пример класс для патерна "реестр" (registry) на php
18.06.2016
В примеси реализованы методы:
- add
- set
- get
- length
- exists
- remove
- keys
В классе:
- toString
- toJson
- loadJSON

main.php (Download)
<?
error_reporting(E_ALL);
ini_set('display_errors', 'On');
$aRet = [];
require_once('class.registry.php');
/**
* Класс для демонстрации реестра
*/
class demoRegistry
{
/**
* Первый тест.
* add, set, remove, toString, toJson
*
* @return string
*/
public function doTest1()
{
ob_start();
echo '<h2>Test 1</h2><p>add, set, remove, toString, toJson</p>';
$oRegistry = new soRegistry();
$oRegistry->add('123', 'Text 123');
$oTmp = new stdClass();
$oTmp->zq = 'wer';
$oTmp->rrrr = 'RRR';
$oRegistry->add('432', $oTmp);
$oRegistry->add('array123', array('my1'=>'123', 'my2' => 555.7) );
echo $oRegistry->toString().'<hr />';
echo $oRegistry->toJson().'<hr />';
$oRegistry->set('123', 'New Text');
$oRegistry->remove('432');
echo $oRegistry->toString().'<hr />';
return ob_get_clean();
}
/**
* Второй тест.
* Загрузка из JSON
*
* @return string
*/
public function doTest2()
{
ob_start();
echo '<h2>Test 2</h2><p>Загрузка из JSON</p>';
$oRegistry = new soRegistry();
$oRegistry->loadJson('{"123":"Text 123","432":{"zq":"wer","rrrr":"RRR"},"array123":{"my1":"123","my2":555.7}}');
echo $oRegistry->toString().'<hr />';
return ob_get_clean();
}
}
$oDemo = new demoRegistry();
$aRet['test1'] = $oDemo->doTest1();
$aRet['test2'] = $oDemo->doTest2();class.registry.php (Download)
<?
# namespace sofw\core;
/**
* Примесь шаблон "реестр".
* Основной костяк
*
*/
trait soTraitRegistry
{
/**
* Массив элементов
*
* @var array
*
*/
protected $_aItems = array();
//------------------------------------------------
/**
* Локальный обработчик ошибок
*
* @param string $sText
*
* @return void
*/
protected function _setError($sText)
{
die($sText);
}
/**
* Устанавливаем значение по ключу.
* Генерирует ошибку, если элемента с таким ключем нет.
*
* @param string $sKey
* @param mixed $Value
*
* @return $this
*/
public function set($sKey, $Value)
{
if ( $this->exists($sKey) )
{
$this->_aItems[$sKey] = $Value;
}
else
{
$this->_setError('Key <b>'.$sKey.'</b> not exists');
}
return $this;
}
/**
* Добавлеяет значение по ключу.
* Генерирует ошибку, если элемента с таким ключем уже есть.
*
* @param string $sKey
* @param mixed $Value
*
* @return $this
*/
public function add($sKey, $Value)
{
if ( !$this->exists($sKey) )
{
$this->_aItems[$sKey] = $Value;
}
else
{
$this->_setError('Key <b>'.$sKey.'</b> exists');
}
return $this;
}
/**
* Получаем значение по ключу.
*
* @param string $sKey
* @param mixed $DefValue
*
* @return mixed
*/
public function get($sKey, $DefValue = NULL)
{
return isset($this->_aItems[$sKey])?$this->_aItems[$sKey]:$DefValue;
}
/**
* Удаляем значение по ключу.
*
* @param string $sKey
*
* @return $this
*/
public function remove($sKey)
{
unset($this->_aItems[$sKey]);
return $this;
}
/**
* Возвращает количество элементов в реестре
*
* @return int
*/
public function length()
{
return count($this->_aItems);
}
/**
* Возвращает все ключи реестра
*
* @return array
*/
public function keys()
{
return array_keys($this->_aItems);
}
/**
* Возвращает True если элемент с таким ключем есть, False в обратном случаи.
*
* @param string $sKey
*
* @return boolean
*/
public function exists($sKey)
{
return isset($this->_aItems[$sKey]);
}
}
/**
* Примесь шаблон "реестр".
* Основной костяк
*
*/
class soRegistry
{
use soTraitRegistry;
/**
* Возвращеает все элементы в виде строки
*
* @return string
*/
public function toString()
{
ob_start();
echo '<pre>';
print_r($this->_aItems);
echo '</pre>';
return ob_get_clean();
}
/**
* Возвращеает все элементы в виде JSON
*
* @return string
*/
public function toJson()
{
return json_encode($this->_aItems);
}
/**
* Загружает элементы из JSON
*
* @param string $sJson
*
* @return string
*/
public function loadJson($sJson)
{
$this->_aItems = json_decode($sJson);
}
}