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

Source: Internet
Author: User
Tags connection pooling

1 Singleton mode Simple Introduction The singleton mode is a frequently used software design pattern.

In its core structure, only a special class called a singleton class is included.

The singleton mode ensures that there is only one instance of a class in the system and that the instance is easily accessible to the outside world. Thus, it is convenient to control the number of instances and save system resources. Suppose you want an object of a class in the system to exist only one. Singleton mode is the best way to solve the problem.


2 mode core idea 1) A class can only have 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, for Memcache and Redis connections, the general requirement is that Redis has only one server, so using a singleton mode to encapsulate the connection to getinstance () has the advantage of not having to call the Connect () method every time to reduce network connection overhead.

PHP is run single-threaded, so the entire program simply instantiates a Redis object. (The project of Clevercode)


4.2 Requirements Analysis     Based on 4.1 can analyze the use of a single case mode is more suitable for PHP network connection operation. such as MySQL. Memcache,redis. Gearman and so on can try a singleton mode. Of course MySQL may involve connection pooling. You just need 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) Singleton 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 Histo RY: *--------------------* 2015/6/8, by Clevercode, Create * */class redisoperate extends redis{ //instance protected 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 History: * --------------------* 2015/6/8, by Clevercode, Create * *///load memcacheinclude_once (' memcacheoperate.php ');//Load Redisi Nclude_once (' redisoperate.php ');/* The client class * separates the client from the business logic as much as possible, reducing the coupling between the client and the business logic algorithm. * Make the algorithm of business logic more portable */class client{/** * Initialize config file * * @return NULL */public static function Initconfi G () {//Memcache host $_server[' 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 Execution Results show

5 Summary 5.1 Advantages

1) Instance Control
The singleton mode prevents other objects from instantiating copies of their own singleton objects, ensuring that all objects have access to the only instance.




2) Flexibility
Because classes control the instantiation process, classes have the flexibility to change the instantiation process.




5.2 Disadvantages

1) Overhead
Although the number is very small, it is still necessary to assume that every time an object requests a reference to check for an instance of the class, there will be some overhead. 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 Newkeyword.

Because you may not be able to access the library source code. As a result, application developers may accidentally 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 includes 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 "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 PHP Project application (23 design mode folders): http://blog.csdn.net/clevercode/article/details/45741843 (folder continuously updated. Attention please bookmark).
4) Blog column address (design mode of PHP Project application): http://blog.csdn.net/column/details/phpusedesignpattern.html (blog continued to add. Attention please bookmark).
5) Welcome everyone to pay attention to Clevercode blog many other wonderful content: Http://blog.csdn.net/CleverCode.

6) Welcome attention to Clevercode Weibo: Http://weibo.com/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.