How to use the single-case PHP model in chicken ribs _ php instances

Source: Internet
Author: User
This article provides a detailed analysis of the php Singleton mode. For more information, see The Singleton mode has three main points:
First, a class can only have one instance;
Second, it must create the instance on its own;
Third, it must provide the instance to the entire system.

The code is as follows:


/* The Singleton mode is used as an example. the main points are as follows:
*
*1. $ _ instance must be declared as a static private variable
* 2. constructor and clone functions must be declared private. this is to prevent external programs from losing the significance of Singleton mode due to new classes.
* 3. the getInstance () method must be declared public and must be called to return a reference to a unique instance.
* 4.: The operator can only access static variables or static functions.
* 5. the single-instance mode of PHP is relatively speaking, because the explain running mechanism of PHP enables all related resources to be recycled after each PHP page is interpreted and executed.
* That is to say, PHP cannot make an object resident in memory at the language level. In PHP, all variables are page-level, regardless of global variables,
* Static members of the class will be cleared after the page is executed, and new objects will be created in the result, which completely loses the meaning of Singleton.
* However, multiple business logic may exist on the same page in actual application. in this case, the singleton mode plays an important role and effectively avoids duplication.
* The new object (note: The new object will consume memory resources) is a behavior, so we say that the single-instance mode of PHP is relatively speaking.
*
*/
Class People
{
Static private $ _ instance = NULL;
Public $ height = '';
Public $ age = '';
Private function _ construct ()
{
$ This-> height = '20140901 ';
$ This-> age = 25;
}
Private function _ clone ()
{
// Do something
}
Static public function getInstance ()
{
If (! Self: $ _ instance instanceof self)
{
// Echo 'lgh-big ';
Self: $ _ instance = new self;
}
Else
{
// For testing only
// Echo 'gdc-xiaoairener ';
}
Return self: $ _ instance;
}
Public function getHeight ()
{
Echo $ this-> height;
}
Public function getAge ()
{
Echo $ this-> age;
}
}
Function testInstance ()
{
People: getInstance ()-> getAge ();
}
// Begin to use the class
$ Lgh = People: getInstance ();
$ Lgh-> getHeight ();
Echo'
';
TestInstance ();
?>


Advantages:The Singleton mode can avoid a large number of new operations, because each new operation consumes memory resources and system resources.
Disadvantages:In PHP, all variables, whether global variables or static members of the class, are page-level. every time a page is executed, a new object is created, will be cleared after the page is executed, so it seems that the PHP Singleton mode is meaningless, therefore, the PHP Singleton mode makes sense only when multiple application scenarios occur during a single page-level request and the same object resource needs to be shared.

Why-Why use the PHP Singleton mode?
One of the main application scenarios of PHP is the application scenario where applications interact with databases. Therefore, a large number of database operations exist in an application. for example, if a database handle is used to connect to a database, the Singleton mode can avoid a large number of new operations, because each new operation consumes memory resources and system resources.
There are still some abstractions to give code snippets.
Use traditional encoding

The code is as follows:


......
// Initialize a database handle
$ Db = new DB (...);
// For example, an application scenario is to add a user information:
$ Db-> addUserInfo ();
......
// However, we may need to find the user information in another place. this scenario appears in a function. in this case, we need to use the database handle resource. we may need to do this.
......
Function test (){
......
// At this time, we have to re-initialize a database handle. imagine how terrible such code is in multiple application scenarios ?!
$ Db = new DB (...);
$ Db-> getUserInfo ();
......
// Some friends may say that I can do the same. can I simply use the global keyword? Indeed, global can solve the problem and play a role in the Singleton mode. However, in OOP, we refuse to write code like this. because global has security risks, please refer to relevant books, at the same time, the singleton mode is precisely an improvement for global variables, avoiding the global variables that store unique instances from polluting the namespace.
In global $ db; // OOP, we do not advocate writing code like this
......
}


Use Singleton mode encoding

The code is as follows:


......
// All application scenarios have only one database handle resource,
// Resources are greatly reduced, and the code is concise and clear :)
DB: getInstance ()-> addUserInfo ();
DB: getInstance ()-> getUserInfo ();
......


How-How to compile the PHP Singleton mode?
After learning about the application scenarios of the Singleton mode, we can write the specific implementation code of the Singleton mode to master the core points of the PHP Singleton mode. the code is as follows:

The code is as follows:


/**
* Example of PHP Singleton mode
* @ Author guohua. li
* @ Modify 2010-07-11
* @ Website http://blog.163.com/lgh_2002/
*/
Class User {
/**
* Save the static finished variable to the global instance
* @ Access private
*/
Static private $ _ instance = NULL;
/**
* Privatize constructors to prevent external instantiation of objects
*/
Private function _ construct (){}
/**
* Privatize clone functions to prevent external clone objects
*/
Private function _ clone (){}
/**
* Static method, uniform single-instance access portal
* @ Return object: unique instance of the returned object
*/
Static public function getInstance (){
If (is_null (self ::$ _ instance) |! Isset (self ::$ _ instance )){
Self: $ _ instance = new self ();
}
Return self: $ _ instance;
}
/**
* Test method: get the username
*/
Public function getName (){
Echo 'hello liguohua! ';
}
}


From the code above, we have summarized the following three core points for implementing the PHP Singleton mode:
1. a static member variable (usually $ _ instance private variable) that stores the unique instance of the class is required)
2. constructor and clone functions must be declared private. this is to prevent external programs from losing the meaning of Singleton mode.
3. a public static method (usually the getInstance method) must be provided to access this instance to return a reference of a unique instance.
Disadvantages of the PHP Singleton mode
As we all know, PHP is an interpreted scripting language. this running mechanism allows every PHP page to be interpreted and executed, and all related resources will be recycled. That is to say, PHP cannot make an object resident in the memory at the language level, which is different from asp.net, Java, and other compilation types, for example, in Java, the single meeting always exists throughout the application lifecycle, and variables are cross-page-level, so that this instance can truly be unique in the application lifecycle. However, in PHP, all variables, whether global variables or static members of the class, are page-level. every time a page is executed, a new object will be created, will be cleared after the page is executed, so it seems that the PHP Singleton mode is meaningless, therefore, the PHP Singleton mode makes sense only when multiple application scenarios occur during a single page-level request and the same object resource needs to be shared.

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.