Hier können Sie sich den Registrierungsmodus auch als Singleton-Version des Kontextobjekts vorstellen.
Eine einfache Registry-Implementierung:
abstract class Registry{ abstract protected function get($key); abstract protected function set($key, $value); }
Datenregistrierungsmodus basierend auf einer HTTP-Anfrage:
class RequestRegistry extends Registry{ private static $instance; private $values = array(); private function __construct(){} static public function instance(){ if(!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; } protected function get($key){ if(isset($this->values[$key])){ return $this->values[$key]; } return null; } protected function set($key, $value){ $this->values[$key] = $value; } static function set_request(Request $request){ self::$instance->set('request', $request); } static function get_request(){ return self::$instance->get('request'); } }
class SessionRegistry extends Registry{ private $instance; private function __construct(){ session_start(); } static function instance(){ if(!isset(self::$instance)){ self::$instance = new self(); } return self::$instance; } protected function get($key){ if(isset($_SESSION[__CLASS__][$key])){ return $_SESSION[__CLASS__][$key] } return null; } protected function set($key, $value){ $_SESSION[__CLASS__][$key] = $value; } public function set_complex(Complex $complex){ self::$instance->set('complex', $complex); } public function get_complex(){ return self::$instance->get('complex'); } }
class ApplicationRegistry extends Registry{ private $dir = "data"; private static $instance; private $values = array(); private $mtimes = array(); private function __construct(){} static function instance(){ if(!isset(self::instance)){ self::$instance = new self(); } return self::$instance; } protected function set($key, $value){ $this->values[$key] = $value; $path = $this->dir . DIRECTORY_SEPARATOR . $key; file_put_contents($path, serialize($value)); $this->mtimes[$key] = time(); } protected function get($key){ $path = $this->dir . DIRECTORY_SEPARATOR . $key; if(file_exists($path)){ $mtime = filetime($path); if(!isset($this->mtimes[$key])) {$this->mtimes[$key] = 0;} if($mtime > $this->mtimes[$key]){ $data = file_get_contents($path); $this->mtimes[$key] = $mtime; return ($this->values[$key] = unserialize($data)); } if(isset($this->values[$key])){ return $this->values[$key]; } } return null; } static function get_dsn(){ return self::$instance->get('dsn'); } static function set_dsn($dsn){ self::$instance->set('dsn', $dsn); } }
Das Obige hat den Registrierungsmodus und einige Aspekte davon vorgestellt. Ich hoffe, dass er Freunden, die sich für PHP-Tutorials interessieren, hilfreich sein wird.