PHP design mode--Singleton mode

Source: Internet
Author: User
Tags php language zend framework

The singleton pattern, as its name implies, is only one instance. As an object's creation mode, Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole. The main points of the singleton pattern are three:
    1. One is that a class can have only one instance;
    2. The second is that it must create this instance on its own;
    3. Thirdly, it must provide this instance to the whole system on its own.
Why use PHP singleton mode
    1. 1. The application of PHP is mainly in the database application, there will be a large number of database operations in an application, when the use of object-oriented development, if the use of Singleton mode, you can avoid a large number of new operations consumed by the resources, but also reduce the database connection so it is not easy to appear too many Connections situation.
    2. 2. If a class is needed in the system to control some configuration information globally, it can be easily implemented using singleton mode. This can be see the Frontcontroller section of the Zend Framework.
    3. 3. In a page request, it is easy to debug, because all the code (such as database Operation class DB) is concentrated in a class, we can set the hooks in the class, output the log, so as to avoid var_dump everywhere, echo.
Example:
1 /**2 * Design pattern of a single case mode3 * $_instance must be declared as a static private variable4 * Constructors must be declared private to prevent the external program new class from losing the meaning of a singleton pattern5 * The getinstance () method must be set to public, and this method must be called to return a reference to the instance6 *:: operator can only access static variables and static functions7 * New objects will consume memory8 * Usage Scenario: The most common place is the database connection. 9 * Once an object is generated using singleton mode, the object can be used by many other objects. Ten  */ One classMans A { -     //Save example instance in this property -     Private Static $_instance; the   -     //The constructor is declared private, preventing the object from being created directly -     Private function__construct () -     { +         Echo' I've been instantiated! ‘; -     } +   A     //Single Case Method at      Public Static functionget_instance () -     { -         Var_dump(isset(Self::$_instance)); -          -         if(!isset(Self::$_instance)) -         { inSelf::$_instance=NewSelf (); -         } to         returnSelf::$_instance; +     } -   the     //prevent users from replicating object instances *     Private function__clone () $     {Panax Notoginseng         Trigger_error(' Clone is not ',E_user_error); -     } the   +     functionTest () A     { the         Echo("Test"); +   -     } $ } $   - //This is an error because the constructor method is declared as private. - //$test = new man; the   - ///The following will get the singleton object of the example classWuyi $test= Man::get_instance (); the $test= Man::get_instance (); - $test-test (); Wu   - //copying an object will result in a e_user_error. About //$test _clone = Clone $test;
The main points of the singleton pattern are three: one is that a class can have only one instance, and the other is that it must create this instance on its own, and thirdly, it must provide this instance to the whole system on its own. Advantage: The singleton mode avoids a large number of new operations because each new operation consumes the memory resource and system resource disadvantage: in PHP, all variables, whether global or static, are page-level, and each time the page is executed, a new object is re-created. will be emptied after the page executes, so it seems that PHP singleton mode is meaningless, so PHP singleton mode I think it is very meaningful to have multiple scenarios for a single page-level request and to share the same object resource. why– Why should I use PHP singleton mode? One of the main applications of PHP is application scenarios for dealing with databases, so there are a number of database operations in an application, such as the behavior of database handlers to connect to a database, and the use of Singleton mode to avoid a large number of new operations. Because each new operation consumes memory resources and system resources. There is still some abstraction, given the code snippet. The traditional way to encode the copied code code is as follows:
<?PHP......//initialize a database handle$db=NewDB (.....);//For example, there is an application scenario where you add a user information:$db-adduserinfo ();......//However, in another place we may want to find the user's information, this scenario appears in a function, this time to use the database handle resources, we may need to do so......functionTest () {......//At this point we have to reinitialize a database handle, imagine a number of scenarios, such code is how scary ah?!  $db=NewDB (.....); $db-GetUserInfo ();......//Some friends may say, I can not do this ah, I directly use the Global keyword is not OK? It is true that global solves the problem and acts as a singleton, but in OOP we refuse to write code because global has security implications, refer to the relevant books, and the singleton pattern is just an improvement on the global variables, Avoid global variables that store unique instances pollution namespaces Global $db;//in OOP, we don't advocate writing code like this......}

Use the single-mode encoding to copy the Code code as follows: <?php......//all application scenarios have only one database handle resource, hehe, the efficiency old high,//resources also greatly saved, code concise and clear:) Db::getinstance () Adduserinfo ();D b::getinstance ()->getuserinfo (); how– How to write PHP singleton mode? After understanding the application scenario of the singleton pattern, we can learn the key points of PHP singleton pattern by writing the specific implementation code of the singleton pattern, the code is as follows: Copy code code is as follows:
<?PHP/** * PHP Singleton Demo Example * @author guohua.li * @modify 2010-07-11* @website http://blog.163.com/lgh_2002/*/classuser{/** * Static finished variables save Global instance * @access private*/Static Private $_instance=NULL;/** * Privatization of constructors to prevent external instantiation of objects*/Private function__construct () {}/** * Privatization of cloning functions to prevent external cloning of objects*/Private function__clone () {}/** * static method, single access portal * @return object returns only instance of object*/Static  Public functiongetinstance () {if(Is_null(Self::$_instance) || !isset(Self::$_instance) ) { self::$_instance=NewSelf ();}returnSelf::$_instance;} /** * Test method: Get user name*/ Public functionGetName () {Echo' Hello liguohua! ';}}

From the above code, we summed up the PHP singleton mode implementation of the core points are as follows three: 1. You need a static member variable that holds a unique instance of the class (typically $_ Instance private variable) 2. Constructors and clone functions must be declared private, in order to prevent the external program new class from losing the meaning of the singleton pattern 3. You must provide a public static method that accesses this instance (typically the GetInstance method), which returns a reference to the unique instance of the missing PHP singleton pattern. It is well known that the PHP language is an interpreted scripting language, which allows each PHP page to be interpreted and all related resources will be recycled. In other words, PHP does not have a language level to allow an object to reside in memory, which is different from the compilation of ASP. NET, Java, such as the single-instance in Java has been in the entire application life cycle, variables are cross-page level, It is true that this instance is unique in the application life cycle. However, in PHP, all variables, whether global variables or static members of the class, are page-level, each time the page is executed, the new object will be re-created, will be emptied after the page executes, so it seems that PHP singleton mode is meaningless,   So PHP singleton mode I think it makes sense to just have multiple scenarios for a single page-level request and need to share the same object resource. Wang Zhen Note: Database object instantiation, permission control (background), login user profile, etc., used for basic function development, business level function can seldom be used

PHP design mode--Singleton mode

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.