|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Pattern "Registry" (Structural) |
| 5 | + * This is demo code |
| 6 | + * See for details: http://maxsite.org/page/php-patterns |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * Registry use Multiton |
| 11 | + */ |
| 12 | +trait MultitonTrait |
| 13 | +{ |
| 14 | + private static $list; |
| 15 | + |
| 16 | + public static function getInstance(string $instance = 'default') |
| 17 | + { |
| 18 | + if (empty(self::$list[$instance])) self::$list[$instance] = new static(); |
| 19 | + return self::$list[$instance]; |
| 20 | + } |
| 21 | + |
| 22 | + private function __construct() |
| 23 | + { |
| 24 | + } |
| 25 | + private function __clone() |
| 26 | + { |
| 27 | + } |
| 28 | + private function __wakeup() |
| 29 | + { |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Class Registry |
| 35 | + */ |
| 36 | +class Registry |
| 37 | +{ |
| 38 | + use MultitonTrait; |
| 39 | + |
| 40 | + private $registry = []; |
| 41 | + |
| 42 | + public function set(string $key, $val) |
| 43 | + { |
| 44 | + $this->registry[$key] = $val; |
| 45 | + } |
| 46 | + |
| 47 | + public function get(string $key, $default = false) |
| 48 | + { |
| 49 | + if (isset($this->registry[$key])) |
| 50 | + return $this->registry[$key]; |
| 51 | + else |
| 52 | + return $default; |
| 53 | + } |
| 54 | + |
| 55 | + public function getAll() |
| 56 | + { |
| 57 | + return $this->registry; |
| 58 | + } |
| 59 | + |
| 60 | + public function unset(string $key) |
| 61 | + { |
| 62 | + if (isset($this->registry[$key])) |
| 63 | + unset($this->registry[$key]); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * demo |
| 69 | + */ |
| 70 | + |
| 71 | +echo '<pre>'; // for print in browser |
| 72 | + |
| 73 | +# $r = new Registry(); // Error: Call to private Registry::__construct() |
| 74 | + |
| 75 | +/** |
| 76 | + * get instance |
| 77 | + */ |
| 78 | +$r1 = Registry::getInstance(); // "default" instance |
| 79 | + |
| 80 | +$r1->set('key', 'value'); |
| 81 | + |
| 82 | +print_r($r1->get('key')); |
| 83 | +/** |
| 84 | + value |
| 85 | + */ |
| 86 | + |
| 87 | +$r1->set('key1', 'value1'); |
| 88 | +print_r($r1->get('key1')); |
| 89 | +/** |
| 90 | + value1 |
| 91 | + */ |
| 92 | + |
| 93 | +print_r($r1->getAll()); |
| 94 | +/** |
| 95 | +Array |
| 96 | +( |
| 97 | + [key] => value |
| 98 | + [key1] => value1 |
| 99 | + ) |
| 100 | + */ |
| 101 | + |
| 102 | +echo '<hr>'; |
| 103 | + |
| 104 | +$r2 = Registry::getInstance('myData'); |
| 105 | + |
| 106 | +print_r($r2->getAll()); |
| 107 | +/** |
| 108 | +Array |
| 109 | +( |
| 110 | +) |
| 111 | + */ |
| 112 | + |
| 113 | +$r2->set('key22', 'value22'); |
| 114 | +print_r($r2->getAll()); |
| 115 | +/** |
| 116 | +Array |
| 117 | +( |
| 118 | + [key22] => value22 |
| 119 | +) |
| 120 | + */ |
| 121 | + |
| 122 | +# end of file |
0 commit comments