search
HomeBackend DevelopmentPHP TutorialPHP architecture registry

PHP architecture registry

Nov 12, 2016 am 11:26 AM
Registry

What is registry mode? it's actually really easy!

The role of the registry is to provide system-level object access functions. We often take "global variables are bad" as an article of faith when coding. However, everything has two sides, and global data access is very attractive.

Here comes the problem:

Most systems are divided into several layers, and each layer only communicates with adjacent layers through pre-defined channels. Sharing layers makes the program flexible, and replacing or modifying each layer can minimize the impact on other parts of the system. But what about when you need information in one layer that is not adjacent to another layer?

Option 1: Pass contextual information from one object to another required object through the connection between the layers of the system: pass this information from one object to another object in the system, from a controller responsible for processing the request The object is passed to the object of the business logic layer, and then passed to the object responsible for talking to the database. Of course, you can also pass the ApplicationHelper object, or a specific Context object.

Option 2: The interfaces of all objects must be modified to determine whether the context objects are what they need. Obviously, sometimes this approach breaks loose coupling.

Option 3: Through registry mode. Registry classes provide static methods (or instantiation methods of singleton objects) to allow other objects to access the data in them (usually objects). Every object in the entire system can access these data objects.

Think about the scope of PHP before implementing it:

Scope is usually used to describe the visible program of an object or value in the code. The life cycle of a variable can be measured in time. There are 3 levels of variable scope.

1. HTTP request scope

refers to the cycle from the beginning to the end of an HTTP request.

2. Session scope

PHP has built-in support for session variables. At the end of a request, the session variables are serialized and stored in the file system or database, and then retrieved at the beginning of the next request. The session ID stored in the cookie and passed in the query string are used to track the owner of the session. Therefore, you can think of certain variables as having session-level scope. Using this, you can store objects between several requests and save traces of user access to the database. Of course, be careful not to hold different versions of the same object, so when you save a session object to the database, you need to consider using certain locking strategies.

3. Application Scope

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

The following uses the registry to implement these three scopes. The class diagram is as follows:

PHP architecture registry

<?php
namespace 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(&#39;request&#39;);
    }
    static function setRequest( \woo\controller\Request $request ) {
        return self::instance()->set(&#39;request&#39;, $request );
    }
}
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[__CLASS__][$key];
        }
        return null;
    }
    protected function set( $key, $val ) {
        $_SESSION[__CLASS__][$key] = $val;
    }
    function setComplex( Complex $complex ) {
        self::instance()->set(&#39;complex&#39;, $complex);
    }
    function getComplex( ) {
        return self::instance()->get(&#39;complex&#39;);
    }
}
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::$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(&#39;dsn&#39;);
    }
    static function setDSN( $dsn ) {
        return self::instance()->set(&#39;dsn&#39;, $dsn);
    }
    static function setControllerMap( \woo\controller\ControllerMap $map  ) {
        self::instance()->set( &#39;cmap&#39;, $map );
    }
    static function getControllerMap() {
        return self::instance()->get( &#39;cmap&#39; );
    }
    static function appController() {
        $obj = self::instance();
        if ( ! isset( $obj->appController ) ) {
            $cmap = $obj->getControllerMap();
            $obj->appController = new \woo\controller\AppController( $cmap );
        }
        return $obj->appController;
    }
}
//如果你安装了PHP的shm扩展,就可以使用该扩展中函数来实现应用程序注册表
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::DSN);
    }
    static function setDSN( $dsn ) {
        return self::instance()->set(self::DSN, $dsn);
    }
}
?>


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor