Detailed application of PHP Singleton pattern of chicken rib

  • 2020-06-03 06:05:07
  • OfStack

There are three main points of the singleton pattern:
One is that a class can only have one instance;
2 is that it has to create the instance itself;
3 it must provide this instance to the whole system itself.

<?php 
/*  Examples of singleton patterns , The main points are as follows : 
* 
* 1. $_instance  Must be declared as a static private variable  
* 2.  Constructors and clones must be declared private , This is to prevent external programs  new  Class thus loses the meaning of the singleton pattern  
* 3. getInstance() Methods must be declared public , This method must be called to return only 1 The instance 1 A reference  
* 4. :: Operators can only access static variables or static functions  
* 5. PHP The singleton pattern is relative , because PHP The explain running mechanism makes each PHP After the page is interpreted and executed, all related resources are recycled.  
*  In other words, PHP There is no way to have an object resident in memory at the language level. in PHP , all variables are page level, whether global variables,  
*  Static members of the class are cleared after the page completes execution , As a result, new objects are created, and they are completely lost Singleton The meaning of.  
*  However, , In practical application 1 There may be more than one business logic in a page , This is where the singleton pattern comes in , Effectively avoids duplication  
* new  object ( note : new  Objects consume memory resources ) so 1 A behavior , So let's say PHP The singleton pattern is relative  
* 
*/ 
class People 
{ 
static private $_instance = NULL; 
public $height = ''; 
public $age = ''; 
private function __construct() 
{ 
$this->height = '185'; 
$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 '<br />'; 
testInstance(); 
?>

Advantages: The singleton avoids a large number of new operations, as each new operation consumes memory and system resources
Disadvantages: in PHP, all variables are global variables and static members of a class, are the page level, each page is performed, will establish a new object, will be cleared after the page has been completed, this seems to be PHP singleton pattern does not make sense, so PHP singleton pattern I think is only for a single page level requests appear many application scenarios and need to share the same 1 object resources makes sense.

Why use the PHP singleton pattern?
PHP 1 main applications is application to deal with the database application scenarios, so there are a lot of in the application of a database operations, such as a database handle to connect to the database this 1 behavior, using a singleton pattern can avoid a lot of new operation, because each one new operation consumes memory and system resources.
Again, a little bit of abstraction, given the code snippets.
Code in the traditional way

<?php
......
// Initialize the 1 A database handle 
$db = new DB(...);
// So let's say we have an application scenario where we add 1 User information: 
$db->addUserInfo();
......
// However, we are in another 1 A place might want to look up user information, this scenario appears in 1 In this case, the database handle resource will be used, which we may need to do 
......
function test(){
 ......
// At this point we have to reinitialize 1 A database handle , Imagine how scary this code would be in multiple application scenarios. ! 
 $db = new DB(...);
 $db->getUserInfo();
 ......
// Some friends might say, Well, I don't have to do that. I just use it global Keyword not ok? Indeed, global Can solve the problem, also plays the role of singleton pattern, but OOP , we refuse to write code this way because global There is a security risk, please refer to the relevant books, and singleton mode is exactly for global variables 1 A kind of improvement to avoid those storage only 1 Instance global variables pollute namespaces 
 global $db;  //OOP We do not advocate writing code in this way 
......
}

Code using singleton pattern

<?php
......
// All the application scenarios are only 1 A database handle resource, hey, that's too efficient, 
// Resources are also greatly saved and the code is simple and clear :) 
DB::getInstance()->addUserInfo();
DB::getInstance()->getUserInfo();
......

How do I write the PHP singleton pattern?
After understanding the application scenario of the singleton pattern, we master the core points of PHP singleton pattern by writing the specific implementation code of the singleton pattern as follows:

<?php
/**
 *  PHP Examples of singleton patterns 
*  @author   guohua.li
 *  @modify  2010-07-11
*  @website  http://blog.163.com/lgh_2002/
*/
class User{
/**
 *   Static finished product variable   Save 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 clones 
*/
private function  __clone(){}
/**
 *   A static method ,  Singleton series 1 Access to the entry 
 *  @return  object   Returns the only of the object 1 The instance 
*/
static public function getInstance() {
if (is_null(self::$_instance) || !isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
} 
   /**
 *  The test method :  Get the user name 
*/
public function getName() {
echo 'hello liguohua!';
}
}

From the above code, we summarize the core points of the PHP singleton pattern implementation as follows:
1. Need a static member variable (usually $_instance private variable) to hold only one instance of the class
2. Constructors and clones must be declared private to prevent the external program new class from losing its meaning as a singleton
3. A public static method (usually getInstance) must be provided to access the instance, thus returning a reference to the only instance
Disadvantages of the PHP singleton pattern
As we all know, PHP is an interpreted scripting language, and this mechanism enables all related resources to be recycled after each PHP page is interpreted and executed. In other words, PHP has no way to make an object resident in memory at the language level, which is different from compilation types such as ES48en.net and Java. For example, in Java, single case 1 exists directly in the entire application life cycle, variables are cross-page level, which can really make this instance unique in the application life cycle. In PHP, however, all of the variables are global variables and static members of a class, are the page level, each page is performed, will establish a new object, will be cleared after the page has been completed, this seems to be PHP singleton pattern does not make sense, so PHP singleton pattern I think just appeared on a single page level requests multiple scenarios and need to share the same 1 object resources makes sense.

Related articles: