PHP Singleton mode is what php implements Singleton mode _ php instance

Source: Internet
Author: User
Tags learn php programming what php
What is the PHP Singleton mode? This article mainly introduces how to implement the singleton mode in php and tells you why the singleton mode is used. If you are interested, refer 1. What is Singleton mode?
1. Meaning
As the object creation mode, the singleton mode ensures that a class has only one instance, and the instance is self-instantiated and global to the entire system. It does not create instance copies, but returns a reference to the instance stored in the singleton class.
2. Three Key Points of Singleton mode:
(1). A static member variable is required to save the unique instance of the class:
Private static $ _ instance;
(2) constructor and clone functions must be declared private to prevent external programs from losing the meaning of Singleton mode due to new classes:

Private function _ construct () {$ this-> _ db = pg_connect ('xxx');} private function _ clone () {}// overwrite _ clone () method, clone prohibited

(3) You must provide a public static method (usually the getInstance method) to access this instance, and return a reference of a unique instance.

public static function getInstance()  {    if(! (self::$_instance instanceof self) )    {      self::$_instance = new self();    }   return self::$_instance;   }  

2. Why is the singleton mode used?
1. PHP disadvantages:

PHP is an interpreted scripting language. This running mechanism allows 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 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.

2. Application of Singleton mode in PHP:
(1) interaction between applications and databases
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 both memory and system resources.
(2) control configuration information
If you need a class in the system to globally control some configuration information, you can easily implement it using the singleton mode.

3. How to Implement the singleton mode?
1. Common Database Access example:

<? Php ...... // initialize a database handle $ db = new DB (...); // Add User Information $ db-> addUserInfo (...);...... // access the database in the function and find the user information function getUserInfo () {$ db = new DB (...); // new database class again, establish a connection with the database $ db = query (....); // access the database according to the query statement}?>

2. perform database operations in the application Singleton mode:

<? Php class DB {private $ _ db; private static $ _ instance; private function _ construct (...) {$ this-> _ db = pg_connect (...); // postgrsql} private function _ clone () {}; // overwrite the _ clone () method. clone of 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 (...);?>

The following code encapsulates the PDO operation database class and adopts the singleton mode:

<? Php/*** MyPDO */class MyPDO {protected static $ _ instance = null; protected $ dbName = ''; protected $ dsn; protected $ dbh; /*** construct ** @ return MyPDO */private function _ construct ($ dbHost, $ dbUser, $ dbPasswd, $ dbName, $ dbCharset) {try {$ this-> dsn = 'mysql: host = '. $ dbHost. '; dbname = '. $ dbName; $ this-> dbh = new PDO ($ this-> dsn, $ dbUser, $ dbPasswd); $ this-> dbh-> exec ('set character_set_connection = '. $ dbC Harset. ', character_set_results = '. $ dbCharset. ', character_set_client = binary');} catch (PDOException $ e) {$ this-> outputError ($ e-> getMessage ());}} /*** prevent cloning **/private function _ clone () {}/*** Singleton instance ** @ return Object */public static function getInstance ($ dbHost, $ dbUser, $ dbPasswd, $ dbName, $ dbCharset) {if (self ::$ _ instance === null) {self ::$ _ instance = new self ($ dbHost, $ DbUser, $ dbPasswd, $ dbName, $ dbCharset);} return self: $ _ instance ;} /*** Query ** @ param String $ strSql SQL statement * @ param String $ queryMode Query method (All or Row) * @ param Boolean $ debug * @ return Array */public function query ($ strSql, $ queryMode = 'all', $ debug = false) {if ($ debug = true) $ this-> debug ($ strSql); $ recordset = $ this-> dbh-> query ($ strSql ); $ this-> getPDOError (); if ($ recordset) {$ r Ecordset-> setFetchMode (PDO: FETCH_ASSOC); if ($ queryMode = 'all') {$ result = $ recordset-> fetchAll ();} elseif ($ queryMode = 'row') {$ result = $ recordset-> fetch () ;}} else {$ result = null;} return $ result ;} /*** Update ** @ param String $ table name * @ param Array $ arrayDataValue field and value * @ param String $ where condition * @ param Boolean $ debug * @ return int */public function update ($ table, $ arrayDa TaValue, $ where = '', $ debug = false) {$ this-> checkFields ($ table, $ arrayDataValue); if ($ where) {$ strSql = ''; foreach ($ arrayDataValue as $ key => $ value) {$ strSql. = ", '$ key' =' $ value'";} $ strSql = substr ($ strSql, 1 ); $ strSql = "updat' $ table 'set $ strSql WHERE $ where";} else {$ strSql = "replace into '$ table '('". implode ('','', array_keys ($ arrayDataValue )). "') VALUES ('". implode ("','", $ ar RayDataValue ). "')";} if ($ debug = true) $ this-> debug ($ strSql ); $ result = $ this-> dbh-> exec ($ strSql); $ this-> getPDOError (); return $ result ;} /*** Insert insert ** @ param String $ table name * @ param Array $ arrayDataValue field and value * @ param Boolean $ debug * @ return Int */public function Insert ($ table, $ arrayDataValue, $ debug = false) {$ this-> checkFields ($ table, $ arrayDataValue); $ strSql = "insert into '$ Table '('". implode ('','', array_keys ($ arrayDataValue )). "') VALUES ('". implode ("','", $ arrayDataValue ). "')"; if ($ debug = true) $ this-> debug ($ strSql); $ result = $ this-> dbh-> exec ($ strSql ); $ this-> getPDOError (); return $ result ;} /*** insert in Replace mode ** @ param String $ table name * @ param Array $ arrayDataValue field and value * @ param Boolean $ debug * @ return Int */public function replace ($ table, $ arrayDataVal Ue, $ debug = false) {$ this-> checkFields ($ table, $ arrayDataValue); $ strSql = "replace into '$ table '('". implode ('','', array_keys ($ arrayDataValue )). "') VALUES ('". implode ("','", $ arrayDataValue ). "')"; if ($ debug = true) $ this-> debug ($ strSql); $ result = $ this-> dbh-> exec ($ strSql ); $ this-> getPDOError (); return $ result;}/*** Delete ** @ param String $ table name * @ param String $ where condition * @ param Boolean $ debug * @ return Int */public function delete ($ table, $ where = '', $ debug = false) {if ($ where = '') {$ this-> outputError ("'where' is Null");} else {$ strSql = "delete from '$ table' WHERE $ WHERE "; if ($ debug = true) $ this-> debug ($ strSql); $ result = $ this-> dbh-> exec ($ strSql ); $ this-> getPDOError (); return $ result;}/*** Execute SQL statement ** @ param String $ strSql * @ param Boolean $ de Bug * @ return Int */public function execSql ($ strSql, $ debug = false) {if ($ debug = true) $ this-> debug ($ strSql ); $ result = $ this-> dbh-> exec ($ strSql); $ this-> getPDOError (); return $ result ;} /*** obtain the maximum value of a field ** @ param string $ table name * @ param string $ field_name field name * @ param string $ where condition */public function getMaxValue ($ table, $ field_name, $ where = '', $ debug = false) {$ strSql =" select max (". $ Field_name. ") AS MAX_VALUE FROM $ table"; if ($ where! = '') $ StrSql. = "WHERE $ where"; if ($ debug = true) $ this-> debug ($ strSql); $ arrTemp = $ this-> query ($ strSql, 'row'); $ maxValue = $ arrTemp ["MAX_VALUE"]; if ($ maxValue = "" | $ maxValue = null) {$ maxValue = 0 ;} return $ maxValue ;} /*** get the number of specified columns ** @ param string $ table * @ param string $ field_name * @ param string $ where * @ param bool $ debug * @ return int */ public function getCount ($ table, $ fie Ld_name, $ where = '', $ debug = false) {$ strSql =" select count ($ field_name) as num from $ table "; if ($ where! = '') $ StrSql. = "WHERE $ where"; if ($ debug = true) $ this-> debug ($ strSql); $ arrTemp = $ this-> query ($ strSql, 'row'); return $ arrTemp ['num'];} /*** get table engine ** @ param String $ dbName database name * @ param String $ tableName table name * @ param Boolean $ debug * @ return String */public function getTableEngine ($ dbName, $ tableName) {$ strSql = "show table status from $ dbName WHERE Name = '". $ tableName. "'"; $ arrayTableInfo = $ This-> query ($ strSql); $ this-> getPDOError (); return $ arrayTableInfo [0] ['engine'];} /*** intransaction transaction start */private function beginTransaction () {$ this-> dbh-> beginTransaction ();} /*** commit transaction commit */private function commit () {$ this-> dbh-> commit ();} /*** rollback transaction rollback */private function rollback () {$ this-> dbh-> rollback ();} /*** transaction: process multiple SQL statements through transactions * getTableEngine must be used to determine the table reference before calling Whether transaction supports transactions ** @ param array $ arraySql * @ return Boolean */public function execTransaction ($ arraySql) {$ retval = 1; $ this-> beginTransaction (); foreach ($ arraySql as $ strSql) {if ($ this-> execSql ($ strSql) = 0) $ retval = 0;} if ($ retval = 0) {$ this-> rollback (); return false;} else {$ this-> commit (); return true ;}} /*** checkFields: Check whether the specified field exists in the specified data table ** @ param String $ table * @ param array $ arra YField */private function checkFields ($ table, $ arrayFields) {$ fields = $ this-> getFields ($ table); foreach ($ arrayFields as $ key => $ value) {if (! In_array ($ key, $ fields) {$ this-> outputError ("Unknown column '$ key' in field list. ") ;}}/ *** getFields: Get all field names in the specified data table ** @ param String $ table name * @ return array */private function getFields ($ table) {$ fields = array (); $ recordset = $ this-> dbh-> query ("show columns from $ table"); $ this-> getPDOError (); $ recordset-> setFetchMode (PDO: FETCH_ASSOC); $ result = $ recordset-> fetchAll (); foreach ($ resu Lt as $ rows) {$ fields [] = $ rows ['field'];} return $ fields ;} /*** getPDOError capture PDO error information */private function getPDOError () {if ($ this-> dbh-> errorCode ()! = '000000') {$ arrayError = $ this-> dbh-> errorInfo (); $ this-> outputError ($ arrayError [2]);} /*** debug ** @ param mixed $ debuginfo */private function debug ($ debuginfo) {var_dump ($ debuginfo); exit ();} /*** output Error message ** @ param String $ strErrMsg */private function outputError ($ strErrMsg) {throw new Exception ('mysql Error :'. $ strErrMsg);}/*** destruct close database connection */public function destruct () {$ th Is-> dbh = null ;}}?>

Call method:

<?phprequire 'MyPDO.class.php';$db = MyPDO::getInstance('localhost', 'root', '123456', 'test', 'utf8');$db->query("select count(*) frome table");$db->destruct();?>

The above is all the content of this article. I hope it will help you learn php programming.

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.