PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 12 ■ ENTERPRISE PATTERNS


As you can see, this class uses the $_SESSION superglobal to set and retrieve values. I kick off the
session in the constructor with the session_start() method. As always with sessions, you must ensure
that you have not yet sent any text to the user before using this class.
As you might expect, the application-level implementation is more of an issue. As with all code
examples in this chapter, this is an illustration rather than production-quality code:


namespace woo\base;
// ...
class ApplicationRegistry extends Registry {
private static $instance;
private $freezedir = "data";
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 get( $key ) {
$path = $this->freezedir. DIRECTORY_SEPARATOR. $key;
if ( file_exists( $path ) ) {
clearstatcache();
$mtime=filemtime( $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;
}
protected function set( $key, $val ) {
$this->values[$key] = $val;
$path = $this->freezedir. DIRECTORY_SEPARATOR. $key;
file_put_contents( $path, serialize( $val ) );
$this->mtimes[$key]=time();
}


static function getDSN() {
return self::instance()->get('dsn');
}

Free download pdf