Home > Article > Backend Development > Getting Started with PHP Design Patterns - Registry Pattern_PHP Tutorial
It’s not easy to summarize the application scenarios of this model. But based on previous experience, registry classes often store some objects that need to be used elsewhere, such as redis, memcache classes, and configuration information config classes, etc. , which plays a role similar to a global variable. The specific implementation is actually very simple, as shown in the following code:
<!--?php class Registry{ static $instance; public $containers = array(); static function getInstance(){ if(is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } public function set($key, $value){ $this--->containers[$key] = $value; } public function get($key){ return isset($this->containers[$key]) ? $this->containers[$key] : null; } } $registry = Registry::getInstance(); $registry->set('key1', 'hello');<span style="white-space:pre"> </span>//只是为了测试,通常注册表中存储的数据都是对象 var_dump($registry->get('key1')); var_dump($registry->get('key2'));