PHP Singleton mode learning Notes

Source: Internet
Author: User
Tags foreach php language rtrim

1. Concept of Singleton mode

As the name suggests, the singleton mode only has one instance and is self-instantiated to provide this instance globally. Note that the singleton mode

Make sure that a class can only have one instance!

2. Three key points of Singleton mode

(1) a static variable is required to save the unique instance of the class.

The code is as follows: Copy code

Private static $ _ instance;

(2) constructor and clone functions must be private to prevent users from creating objects and copying instance objects.

The code is as follows: Copy code

Private function _ construct ()
{
// Default constructor of privatization to prevent external instantiation
}
Private function _ clone ()
{
// Private clone method to prevent users from copying instances
}

(3) a public static method (generally getInstance) must be provided to return a reference to a unique instance.

The code is as follows: Copy code
Public static function getInstance ()
{   
If (! (Self: $ _ instance instanceof self ))
    {   
Self: $ _ instance = new self ();
    } 
Return self: $ _ instance;
 
}

3. Reasons for using Singleton mode in php
The PHP language is an interpreted scripting language. This mechanism enables all related resources after each PHP page is interpreted and executed.

All sources will be recycled. That is to say, PHP cannot make an object resident in memory at the language level, which is compiled with asp.net, Java, and so on.

Type is different. For example, in Java, a single meeting always exists throughout the life cycle of the application, and variables are cross-page-level.

To ensure the uniqueness of the instance in the application lifecycle. However, in PHP, all variables, whether global variables or static classes

Status members are all page-level members. Every time a page is executed, a new object will be created, and the object will be cleared after the page is executed,

In this case, it seems that the PHP Singleton mode is meaningless. Therefore, the single-case PHP mode is only applicable to multiple

It is meaningful when the application scenario needs to share the same object resource.

4. How to implement the Singleton mode

The code is as follows: Copy code

<? Php
/**
* Singleton mode example: Demo
*/
Class Demo {
// Static member variables used to save global instances
Private static $ _ instance;
// Private constructor to ensure that external entities cannot be directly instantiated
Private function _ construct (){

 }
// Private clone method to prevent users from copying instances
Private function _ clone (){

 }
// Return the unique instance of this class
Public function getInstance (){
If (! (Self: $ _ instance instanceof self ))
  {
Self: $ _ instance = new self ();
  }
Return self: $ _ instance;
 }
// This is the first test method.
Public function test1Function (){
Echo 'This is the first test method ';
 }
// This is the second test method.
Public function test2Function (){
Echo 'This is the second Test method ';
 }
}
// Correct usage
@ $ Demo = Demo: getInstance ();
$ Demo-> test1Function ();
$ Demo-> test2Function ();
// This will cause an error in instantiation because the constructor is private.
// $ Demo_new = new Demo;
// An error occurs when copying the demo because the default clone method is private.
// $ Demo_clone = clone $ demo;
?>

5. Single-profit application scenarios


(1) interaction between applications and databases, mostly used for database connection
(2) If a class is required in the system to globally control configuration information, it can be conveniently implemented in the Singleton mode.


1. Common database access example:

The code is as follows: Copy code

<? Php
......
// Initialize a database handle
$ Db = new DB (...);

// Add user information
$ Db-> addUserInfo (...);

......

// Access the database in the function to find the user information
Function getUserInfo ()
{
$ Db = new DB (...); // create a new database class and establish a connection with the database.
$ Db = query (...); // access the database based on the query statement
}

?>

2. Perform database operations in the application Singleton mode:

The code is as follows: Copy code


<? Php

Class DB

Private $ _ db;
Private static $ _ instance;
 
Private function _ construct (...)
    { 
$ This-> _ db = pg_connect (...); // postgrsql
    } 
 
Private function _ clone () {}; // overwrite the _ clone () method to prohibit cloning.
 
Public static function getInstance ()
    { 
If (! (Self: $ _ instance instanceof self )){
Self: $ _ instance = new self ();
        } 
Return self: $ _ instance;
    } 
 
   

Public function addUserInfo (...)
    {

  

    }

Public function getUserInfo (...)
    {

    }

}

// Test

$ Db = DB: getInstance ();

$ Db-> addUserInfo (...);

$ Db-> getUserInfo (...);


?>

In-depth understanding

The code is as follows: Copy code

<? Php
Class db {
Public $ conn;
Public static $ SQL;
Public static $ instance = null;
Private function _ construct (){
Require_once ('Db. config. Php ');
$ This-> conn = mysql_connect ($ db ['host'], $ db ['user'], $ db ['password']);
If (! Mysql_select_db ($ db ['database'], $ this-> conn )){
Echo "failed ";
};
Mysql_query ('set names utf8', $ this-> conn );
 }
Public static function getInstance (){
If (is_null (self: $ instance )){
Self: $ instance = new db;
  }
Return self: $ instance;
 }
/**
* Query a database
*/
Public function select ($ table, $ condition = array (), $ field = array ()){
$ Where = '';
If (! Empty ($ condition )){
   
Foreach ($ condition as $ k => $ v ){
$ Where. = $ k. "= '". $ v. "' and ";
   }
$ Where = 'where'. $ where. '1 = 1 ';
  }
$ Fieldstr = '';
If (! Empty ($ field )){
   
Foreach ($ field as $ k => $ v ){
$ Fieldstr. = $ v .',';
   }
$ Fieldstr = rtrim ($ fieldstr ,',');
} Else {
$ Fieldstr = '*';
  }
Self: $ SQL = "select {$ fieldstr} from {$ table} {$ where }";
$ Result = mysql_query (self: $ SQL, $ this-> conn );
$ ResuleRow = array ();
$ I = 0;
While ($ row = mysql_fetch_assoc ($ result )){
Foreach ($ row as $ k => $ v ){
$ ResuleRow [$ I] [$ k] = $ v;
   }
$ I ++;
  }
Return $ resuleRow;
 }
/**
* Add a record
*/
Public function insert ($ table, $ data ){
$ Values = '';
$ Datas = '';
Foreach ($ data as $ k => $ v ){
$ Values. = $ k .',';
$ Datas. = "'$ V '".',';
   }
$ Values = rtrim ($ values ,',');
$ Datas = rtrim ($ datas ,',');
Self: $ SQL = "INSERT INTO {$ table} ({$ values}) VALUES ({$ datas })";
If (mysql_query (self: $ SQL )){
Return mysql_insert_id ();
} Else {
Return false;
};
  }
/**
* Modify a record
*/
Public function update ($ table, $ data, $ condition = array ()){
$ Where = '';
If (! Empty ($ condition )){
   
Foreach ($ condition as $ k => $ v ){
$ Where. = $ k. "= '". $ v. "' and ";
   }
$ Where = 'where'. $ where. '1 = 1 ';
  }
$ Updatastr = '';
If (! Empty ($ data )){
Foreach ($ data as $ k => $ v ){
$ Updatastr. = $ k. "= '". $ v ."',";
   }
$ Updatastr = 'set'. rtrim ($ updatastr ,',');
  }
Self: $ SQL = "update {$ table} {$ updatastr} {$ where }";
Return mysql_query (self: $ SQL );
 }
/**
* Delete a record
*/
Public function delete ($ table, $ condition ){
$ Where = '';
If (! Empty ($ condition )){
   
Foreach ($ condition as $ k => $ v ){
$ Where. = $ k. "= '". $ v. "' and ";
   }
$ Where = 'where'. $ where. '1 = 1 ';
  }
Self: $ SQL = "delete from {$ table} {$ where }";
Return mysql_query (self: $ SQL );
  
  }
 
Public static function getLastSql (){
Echo self: $ SQL;
 }
 
 
 
}

$ Db = db: getInstance ();
// $ List = $ db-> select ('demo', array ('name' => 'Tom ', 'password' => 'DS'), array

('Name', 'password '));
// Echo $ db-> insert ('demo', array ('name' => 'Recent use', 'password' => '123 '));
// Echo $ db-> update ('demo', array ("name" => 'XXX', "password" => '123 '), array ('id' => 1 ));
Echo $ db-> delete ('demo', array ('id' => '2 '));
Db: getLastSql ();
Echo "<pre> ";
?>

Php has many design patterns. The Singleton mode is a commonly used mode for code writing.

It can effectively reduce the resource consumption of the new operation and easily control some global configuration information! I hope you will learn more in php

Xi has a deep understanding of the application of the Singleton model.

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.