Question:
The Internet is full of examples of this class. But nowhere is it written, but where to store these data.
After all, after reloading the page, all the data that we saved in some internal variable will be lost.
These people know something, but do not speak?
Or does this pattern need to be used in some way with the memcached
store?
Or is the memcached
store just implementing this pattern and you just need to use it?
The only purpose of the pattern is for caching, or is it possible to use it somewhere else? How (if, as I wrote above – the data is erased after a reboot)?
Answer:
The Registry design pattern is not used for caching , but mainly for replacing global variables, because global variables are not very good.
Registry
class Registry
{
/**
* данные реестра
*/
protected static $data = array();
/**
* Добавляет значение в реестр
*
*/
public static function set($key, $value)
{
self::$data[$key] = $value;
}
/**
* Возвращает значение из реестра по ключу
*/
public static function get($key)
{
if(isset(self::$data[$key])) {
return self::$data[$key];
}
return null;
}
/**
* Удаляет значение из реестра по ключу
*
*/
public static function removeVar($key)
{
if(isset(self::$data[$key])) {
unset(self::$data[$key]);
}
}
}
But, unlike global variables, thanks to this pattern, you can add some additional "chips", such as blocking a variable from changing.
Expand opportunities
/**
* Добавим массив с для идентификации залоченных переменых
*/
protected static $locked = array();
/**
* Поменяем метод set из примера выше
*/
static public function set($key, $value) {
if ( !self::hasLock($key) ) {
self::$data[$key] = $value;
} else {
throw new Exception("переменная '$key' заблокирована для изменений");
}
}
/**
* напишем "обвес" для блокировки/разблокировки
*/
static public function lock($key) {
self::$lock[$key] = true;
}
static public function hasLock($key) {
return isset(self::$lock[$key]);
}
static public function unlock($key) {
if ( self::hasLock($key) ) {
unset(self::$lock[$key]);
}
}
And if you need to store data from the Registry somewhere, then you can easily write it anywhere.