Singleton mode is a PHP in order to simplify the development and repeated calls a function, let me give you a detailed introduction of the singleton mode usage.
1. The concept of singleton mode
As the name implies, the singleton pattern has only one instance and is instantiated by itself, providing this instance to the global. It should be emphasized that the singleton mode
Make sure that a class can have only one instance!
2. Three points of a singleton pattern
(1) A static variable is required to hold the unique instance of the class
The code is as follows |
Copy Code |
private static $_instance; |
(2) Constructors 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 () { Privatization of default construction methods to prevent direct instantiation of the outside world } Private Function __clone () { Privatization cloning method to prevent users from replicating instances } |
(3) A public static method (typically 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;
}
|
Reasons for using singleton mode in 3.php
The PHP language is an interpreted scripting language, which allows each PHP page to be interpreted and executed, all the relevant resources
The source will be recycled. In other words, PHP does not have a language level to allow an object to reside in memory, which is compiled with ASP. NET, Java, etc.
Types are different, such as in Java, where a single-instance is always present throughout the life of the application, variables are cross-page and can really
To achieve the uniqueness of this instance in the application life cycle. In PHP, however, all variables, whether global variables or class statics, are
State members, are page-level, each time the page is executed, the new object will be re-established, will be emptied after the page executes,
This seems like PHP singleton mode is meaningless, so PHP singleton mode I think only for a single page-level request when there are multiple
It makes sense to apply scenarios and share the same object resources.
4. How to implement a singleton mode
The code is as follows |
Copy Code |
< p>!--? php /** * Singleton mode example: Demo */ Class demo{ //static member variable to hold global instance private static $_instance; Privatization of construction methods to ensure that the outside world cannot directly instantiate the Private function __construct () { } //Privatization cloning method to prevent users from replicating instances Private function __clone () { } //Return 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 method of Use @ $demo = Demo::getinstance (); $demo->test1function (); $demo->test2function (); //This instantiation is an error because the constructor is private //$demo _new = new Demo; Copying the demo will make an error because the default clone method is private //$demo _clone = Clone $demo; ? |
5. Application of simple interest mode
(1) Application and database interaction, more for the database connection
(2) If a class is needed in the system to control the configuration information globally, the singleton mode can be easily implemented.
1. Common Database Access Examples:
The code is as follows |
Copy Code |
...... Initialize a database handle $db = new db (...); Add user Information $db->adduserinfo (...); ...... Accessing the database in a function to find user information function GetUserInfo () { $db = new db (...); /again new database class, and database establish connection $db = Query (...); /database access based on query statement } ?> |
2, apply the singleton mode to the database operation:
code as follows |
copy code |
Class DB { Private $_db; private static $_instance;
Private function __construct (...) { $this->_db = Pg_connect (...); /postgrsql }
Private Function __clone () {}; Overwrite __clone () method, 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 (...); ?>
|
Deep understanding
The code is as follows |
Copy Code |
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 "Failure"; }; mysql_query (' Set names UTF8 ', $this->conn); } public static function getinstance () { if (Is_null (self:: $instance)) { Self:: $instance = new db; } Return self:: $instance; } /** * Query 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 Records */ 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 you ', ' password ' = ' 123 ')); echo $db->update (' demo ', Array ("name" = ' xxx ', "password" = ' 123 '), array (' ID ' =>1)); echo $db->delete (' demo ', Array (' id ' = ' 2 ')); Db::getlastsql (); echo " "; ?>
|
PHP has a lot of design patterns, and the singleton mode is the most common mode when we write code, it can not only
Effectively reduce the resource consumption of new operations, and can easily control some of the global configuration information! I hope everyone in the PHP study
Understanding of the application of the singleton model.
http://www.bkjia.com/PHPjc/628672.html www.bkjia.com true http://www.bkjia.com/PHPjc/628672.html techarticle Singleton mode is a PHP in order to simplify the development and repeated calls a function, let me give you a detailed introduction of the singleton mode usage. 1. The concept of a singleton pattern, as the name implies, ...