PHP Singleton mode is what php implements Singleton mode, php mode_php tutorial

Source: Internet
Author: User
Tags learn php programming what php
PHP Singleton mode is what php implements Singleton mode, php mode. What is the PHP Singleton mode for implementing the Singleton mode? php pattern 1. what is Singleton mode? 1. meaning as the object creation mode. Singleton mode ensures that a class has only one PHP Singleton mode. what is the php Singleton mode for implementing Singleton mode? php mode

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.

Using php to implement the Singleton mode: php mode 1. what is Singleton mode? 1. meaning is used as the object creation mode. Singleton mode ensures that a class has only one...

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.