여기서 등록 모드를 컨텍스트 개체의 싱글톤 버전으로 생각할 수도 있습니다.
간단한 레지스트리 구현:
abstract class Registry{ abstract protected function get($key); abstract protected function set($key, $value); }
단일 HTTP 요청 기반 데이터 등록 모드:
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); } }
위의 내용은 레지스트리 모드를 소개하며, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.