Registry of PHP schemas

Source: Internet
Author: User
Tags session id variable scope
What is the registry mode? It's really simple!

The purpose of the registry is to provide system-level object access functionality. We often put "global variables as bad" as a creed when coding. However, there are two sides to everything, and global data access is very attractive.

Here's the problem:

Most systems are divided into layers, each of which is communicated only through pre-defined channels and adjacent layers. The sharing of layers makes the program flexible, and replacing or modifying each layer minimizes the impact on other parts of the system. But what if you need to get the information you need in a layer that is not adjacent to another layer?

Scenario One: The context information is passed from one object to another, through a connection between the layers of the system: This information is passed from one object to another in the system, from a controller object responsible for processing the request to the object of the business logic layer, and then to the object responsible for and the database conversation. Of course, you can also pass a Applicationhelper object, or a specific context object.

Scenario Two: You must modify the interfaces of all objects to determine whether the context objects are required by them. Obviously, sometimes this scenario destroys loose coupling.

Scenario Three: Through the registry mode. The registry class provides static methods (or instantiation methods for singleton objects) to allow other objects to access data (usually objects) within them. These data objects are accessible to every object in the entire system.

Consider the scope of PHP before you implement it:

Scopes are typically used to describe a visible program of objects or values in code, and the life cycle of a variable can be measured in time, with 3 levels of variable scope.

One, HTTP request scope

Refers to the period from start to end of an HTTP request.

Second, session scope

PHP has built-in support for session variables. At the end of a request, the session variable is serialized and stored in the file system or database, and then retrieved at the start of the next request. The session ID that is stored in the cookie and the session ID passed through the query string are used to track the owner of the session. Therefore, you can assume that certain variables have session-level scopes. With this, objects can be stored between several requests, saving the traces of user access to the database. Of course, be careful to avoid having different versions of the same object, so when you save a session object to the database, you need to consider using a certain locking strategy.

III. Application Scope

In other languages, especially Java, there is the concept of a cache pool, the "Application scope". Variables in memory can be accessed by all object instances in the program. PHP has no such functionality, but in large-scale applications, accessing application-level data is useful in order to access configuration variables.

The following is a registry implementation of these three scopes, the class diagram is as follows:

<?phpnamespace woo\base;require_once ("woo/controller/appcontroller.php"); abstract class Registry {abstract    protected function get ($key); Abstract protected function set ($key, $val);}    Class Requestregistry extends Registry {private $values = array ();    private static $instance;  Private Function __construct () {} static 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, $val) {$this->values[$key] = $val;    } static function Getrequest () {return self::instance ()->get (' request '); } static function Setrequest (\woo\controller\request $request) {return self::instance ()->set (' Request ', $r    Equest); }}class Sessionregistry extends Registry {private STATic $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[__CL        ass__][$key];    } return null;    } protected function set ($key, $val) {$_session[__class__][$key] = $val;    } function Setcomplex (Complex $complex) {self::instance ()->set (' Complex ', $complex);    } function Getcomplex () {return self::instance ()->get (' Complex ');    }}class Applicationregistry extends Registry {private static $instance;    Private $freezedir = "/tmp/data";    Private $values = Array ();    Private $mtimes = Array (); Private Function __construct () {} static function instance () {if (! Isset (self:: $instance)) {self:: $instanc E = 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 '); } statIC function Setdsn ($DSN) {return self::instance ()->set (' DSN ', $DSN); } static function Setcontrollermap (\woo\controller\controllermap $map) {self::instance ()->set (' CMap ', $m    AP);    } static function Getcontrollermap () {return self::instance ()->get (' CMap ');        } static function AppController () {$obj = Self::instance ();            if (! isset ($obj->appcontroller)) {$cmap = $obj->getcontrollermap ();        $obj->appcontroller = new \woo\controller\appcontroller ($CMAP);    } return $obj->appcontroller;    }}//If you install the PHP shm extension, you can use the extension function to implement the application Registry class Memapplicationregistry extends Registry {private static $instance;    Private $values =array ();    Private $id;    Const Dsn=1;        Private Function __construct () {$this->id = @shm_attach (55, 10000, 0600);        if (! $this->id) {throw new Exception ("Could not access shared memory"); }} Static FunCtion instance () {if (! Isset (self:: $instance)) {self:: $instance = new self ();}    Return self:: $instance;    } protected function Get ($key) {return Shm_get_var ($this->id, $key);    } protected function set ($key, $val) {return Shm_put_var ($this->id, $key, $val);    } static function Getdsn () {return self::instance ()->get (self::D sn);    } static function Setdsn ($DSN) {return self::instance ()->set (self::D sn, $DSN); }}?>
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.