PHP Project Application of design pattern--a singleton pattern design memcache and Redis operation class

Source: Internet
Author: User
Tags connection pooling

1 Single example mode the singleton mode is a common software design pattern. In its core structure, it contains only a special class called a singleton class. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system.


2 mode core idea 1) A class can have only one instance;
2) It must create this instance on its own;

3) It must provide this instance to the entire system on its own.


3 schema Diagram

4 Project Application 4.1 requirement description Clevercode in the actual PHP project, the application of the singleton mode is related to the network connection. For example, Memcache and Redis connections, the general requirements of Redis are usually only one server, so in a singleton mode to encapsulate the connection to getinstance (), the advantage is not to call the Connect () method every time, reduce network connection overhead. PHP is a single-threaded synchronous execution, so the entire program only instantiates a Redis object. (The "Clevercode Project")


4.2 Requirement Analysis According to 4.1, we can analyze the operation of using singleton mode to compare with PHP network connection. You can try a singleton mode, such as Mysql,memcache,redis,gearman. Of course, MySQL may involve connection pooling, just to turn the singleton into an array single case. i.e. $_instance = null, becomes $_instance = Array (), $_instance[' con1 '] = new self (' conn1 '); $_instance[' con2 '] = new self (' conn2 ');


4.3 Program source code Download http://download.csdn.net/detail/clevercode/8783989

4.4 Program Description

Memcache and Redis need to be added to the PHP extension in advance.


1) Single case mode design Memcache operation Class (memcacheoperate.php)
<?php/** * memcacheoperate.php * * Single case mode design Memcache Operation class * * Copyright (c) http://blog.csdn.net/CleverCode * * modific  ation: *--------------------* 2015/6/8, by Clevercode, Create * */class memcacheoperate extends memcache{        // Instance    protected static $_instance = null;    /**     * Singleton instance (get your own instance)     *     * @return memcacheoperate */public    static function GetInstance () {        if (null = = = self::$_instance) {                        self::$_instance = new self ();            $host = $_server[' memcache_host ');            $port = $_server[' Memcache_port ');            Self::$_instance->addserver ($host, $port);        }        return self::$_instance;}    }




2) Single-case mode design Redis operations Class (redisoperate.php)
<?php/** * redisoperate.php * * Single-mode design Redis Operation class * * Copyright (c) http://blog.csdn.net/CleverCode * * Modification History: *--------------------* 2015/6/8, by Clevercode, Create * */class redisoperate extends redis{        //Instance    prot ected static $_instance = null;    /**     * Singleton instance (get your own instance)     *     * @return redisoperate     *    /public static function getinstance ( {        if (null = = self::$_instance) {                        self::$_instance = new self ();            $host = $_server[' redis_host ');            $port = $_server[' Redis_port ');            Self::$_instance->connect ($host, $port);        }        return self::$_instance;}    }




3) client code (singletonpattern.php)

<?php/** * singletonpattern.php * * Single case Mode * * Copyright (c) http://blog.csdn.net/CleverCode * * Modification Histo RY: *--------------------* 2015/6/8, by Clevercode, Create * *///load memcacheinclude_once (' memcacheoperate.php ');//Load RE      Disinclude_once (' redisoperate.php '); */* Client class * Allows the client and business logic to be separated as much as possible, reducing the coupling between client and business logic algorithms, making the algorithm of business logic more portable */class client{/** * Initialize config file * * @return NULL */public static function Initconfig () {//Memcache host $_serv                er[' memcache_host '] = ' 192.168.6.201 ';                Memcache Port $_server[' memcache_port '] = 11211;                Redis host $_server[' redis_host '] = ' 192.168.6.201 ';    Redis Port $_server[' redis_port '] = 6379;                }/** * Main function * * @return NULL */Public Function main () {//Initialize configuration self::initconfig ();        Memcache key1 memcacheoperate::getinstance ()->set (' Key1 ', ' Memcache CleverCode1 ', 0, 100); Echo MEMCACheoperate::getinstance ()->get (' Key1 ');                echo "\ r \ n---\ r \ n";        Memcache key2 memcacheoperate::getinstance ()->set (' Key2 ', ' Memcache CleverCode2 ', 0, 100);        Echo memcacheoperate::getinstance ()->get (' Key2 ');                echo "\ r \ n---\ r \ n";        Redis Key3 redisoperate::getinstance ()->set (' Key3 ', ' Redis CleverCode3 ');        Echo redisoperate::getinstance ()->get (' Key3 ');                echo "\ r \ n---\ r \ n";        Redis key4 redisoperate::getinstance ()->set (' Key4 ', ' Redis CleverCode4 ');        Echo redisoperate::getinstance ()->get (' Key4 ');    echo "\ r \ n---\ r \ n";    }}/** * Program Entry */function start () {$client = new client (); $client->main ();} Start ();? >


4.5 Program Run results show

5 Summary 5.1 Benefits

1) Instance Control
Singleton mode prevents other objects from instantiating copies of their own singleton objects, ensuring that all objects have access to unique instances.


2) Flexibility
Because classes control the instantiation process, classes can flexibly change the instantiation process.


5.2 Disadvantages

1) Overhead
Although the number is small, there will still be some overhead if you want to check for instances of the class every time the object requests a reference. This problem can be resolved by using static initialization.


2) Possible development confusion
When using singleton objects, especially those defined in a class library, developers must remember that they cannot instantiate objects using the New keyword. Because library source code may not be accessible, application developers may unexpectedly find themselves unable to instantiate this class directly.


3) Object lifetime
The problem of deleting a single object cannot be resolved. In a language that provides memory management, such as a. NET framework-based language, only a singleton class can cause an instance to be deallocated because it contains a private reference to the instance. In some languages, such as C + +, other classes can delete object instances, but this results in a floating reference in a singleton class.

Copyright Notice:1) original works, from the "Clevercode blog", is strictly prohibited reprint, otherwise hold the copyright legal responsibility.
2) Original address: http://blog.csdn.net/clevercode/article/details/46410055.
3) design mode of PHP Project application (23 Design Patterns directory): http://blog.csdn.net/clevercode/article/details/45741843 (Directory continuous update, attention please favorites).
4) Blog column address (design mode of the PHP project application): http://blog.csdn.net/column/details/phpusedesignpattern.html (blog continues to increase, concern please collection).
5) Welcome everyone to pay attention to my blog more wonderful content: Http://blog.csdn.net/CleverCode.





PHP Project Application of design pattern--a singleton pattern design memcache and Redis operation class

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.