PHP singleton mode is what PHP implements a singleton mode method, PHP mode _php tutorial

Source: Internet
Author: User
Tags dsn learn php learn php programming what php

PHP singleton mode is what PHP implements a singleton mode, PHP mode


First, what is a singleton mode?
1. Meaning
As an object's creation mode, Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the whole system globally. Instead of creating an instance copy, it returns a reference to the instance stored inside the singleton class.
2. Three points of the singleton mode:
(1). You need a static member variable that holds a unique instance of the class:
private static $_instance;
(2). Constructors and clone functions must be declared private to prevent the external program new class from losing the meaning of the singleton pattern:

Private Function __construct ()  {    $this->_db = Pg_connect (' xxxx ');}  

(3). You must provide a public static method that accesses this instance (typically the GetInstance method), which returns a reference to the unique instance

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

Second, why should I use a singleton mode?
1. PHP Disadvantages:

The PHP language is an interpreted scripting language that allows every PHP page to be interpreted, and all related resources will be recycled. In other words, PHP does not have a language level to allow an object to reside in memory, which is different from the compilation of ASP. NET, Java, such as the single-instance in Java has been in the entire application life cycle, variables are cross-page level, It is true that this instance is unique in the application life cycle. However, in PHP, all variables, whether global variables or static members of the class, are page-level, each time the page is executed, the new object will be re-created, will be emptied after the page executes, so it seems that PHP singleton mode is meaningless, So PHP singleton mode I think it makes sense to just have multiple scenarios for a single page-level request and need to share the same object resource.

2, the single case mode in PHP application occasions:
(1), Application and database interaction
A large number of database operations exist in an application, such as a database handle to connect to a database, and a singleton pattern avoids a large number of new operations, because each new operation consumes memory resources and system resources.
(2), control configuration information
If a class is needed in the system to control some configuration information globally, it can be easily implemented using singleton mode.

Third, how to achieve a single case mode?
1. Common Database Access Examples:

<?php ...//Initialize a database handle $db = new db (...);  Add user Information $db->adduserinfo (...);  ......  Access the database in the function, find the user information function GetUserInfo () {   $db = new db (...); /New Database class, establish connection to database   $db = query (...); /Access database based on query statement}  

2, apply the singleton mode to the database operation:

<?php class DB  {    private $_db;    private static $_instance;      Private function __construct (...)    {      $this->_db = Pg_connect (...); /postgrsql    }      Private Function __clone () {};//overwrite __clone () method, disable cloning public      static function getinstance () c17/>{      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 is an encapsulation of the PDO operations database class, using a singleton pattern:

<?php/** * mypdo */class mypdo{protected static $_instance = NULL;  protected $dbName = ";  protected $dsn;    protected $DBH;    /** * Construction * * @return MYPDO */Private Function __construct ($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset) { try {$this->dsn = ' mysql:host= '. $dbHost. ';      Dbname= '. $dbName;      $this-&GT;DBH = new PDO ($this->dsn, $dbUser, $DBPASSWD); $this->dbh->exec (' SET character_set_connection= '. $dbCharset. ', 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 Query * * @param string $STRSQL SQL statement * @param string $queryMode Query method (all or Row) * @param Boolean $debug * @retu RN Array */Public Function query ($STRSQL, $queryMode = ' all ', $debug = False) {if ($debug = = = True) $this->deb    UG ($STRSQL);    $recordset = $this->dbh->query ($STRSQL);    $this->getpdoerror ();      if ($recordset) {$recordset->setfetchmode (PDO::FETCH_ASSOC);      if ($queryMode = = ' All ') {$result = $recordset->fetchall ();      } elseif ($queryMode = = ' Row ') {$result = $recordset->fetch ();    }} else {$result = null;  } return $result;   }/** * Update updated * * @param string $table table name * @param Array $arrayDataValue field and value * @param String $where condition * @param Boolean $debug * @return Int */Public Function update ($table, $arrayDataValue, $where = ", $debug = False    ) {$this->checkfields ($table, $arrayDataValue);      if ($where) {$strSql = '; foreach ($arrayDataValue as $key = $value) {$strSql. = ", ' $key ' = ' $value '";      } $STRSQL = substr ($STRSQL, 1);    $STRSQL = "UPDATE ' $table ' SET $strSql WHERE $where"; } else {$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;  }/** * Insert inserts * * @param String $table table name * @param Array $arrayDataValue field and value * @param Boolean $debug * @return Int */Public Function Insert ($table, $arrayDataValue, $debug = False) {$this->checkfields ($table, $ar    Raydatavalue); $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;  }  /** * Replace Overlay Method Insert * * @param String $table table name * @param Array $arrayDataValue field and value * @param Boolean $debug * @return Int */Public function replace ($table, $arrayDataValue, $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 Deletes * * @param string $table table name * @param string $where condition * @param Boolean $debug * @return I NT/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; }}/** * execsql Execute SQL statement * * @param String $STRSQL * @param Boolean $debug * @return Int */Public funct    Ion Execsql ($STRSQL, $debug = False) {if ($debug = = = True) $this->debug ($STRSQL);    $result = $this->dbh->exec ($STRSQL);    $this->getpdoerror ();  return $result;  }/** * gets field maximum * * @param string $table 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; /** * Gets the number of specified columns * * @param string $table * @param string $field _name * @param string $where * @param boOL $debug * @return int */Public Function GetCount ($table, $field _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 '];  }/** * Gets the table engine * * @param string $dbName Library name * @param string $tableName table name * @param Boolean $debug * @return String */Public Function gettableengine ($dbName, $tableName) {$strSql = ' SHOW TABLE STATUS from $dbName WHERE Na    Me= ' ". $tableName." ";    $arrayTableInfo = $this->query ($STRSQL);    $this->getpdoerror ();  return $arrayTableInfo [0][' Engine '];  }/** * BeginTransaction 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 to determine whether the table engine supports transactions by Gettableengine before calling through a Transact-SQL statement * * @param array $arraySql * @return Bool    EAN */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 checks whether the specified field exists in the specified data table * * @param String $table * @param array $arrayField */Private FUNCTI    On Checkfields ($table, $arrayFields) {$fields = $this->getfields ($table); foreach ($arrayFields as $key = + $value) {if (!in_array ($key, $fields)) {$this->outputerror ("Unknown C    Olumn ' $key ' in field list. ");}} /** * GetFields gets all field names in the specified data table * * @param String $table 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 ($result as $rows) {$fields [] = $rows [' Field '];  } return $fields; }/** * Getpdoerror capturing PDO error message */Private function Getpdoerror () {if ($this->dbh->errorcode ()! = ' 00000 '      ) {$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 excep  tion (' MySQL Error: '. $strErrMsg);  }/** * Destruct close database connection */Public Function destruct () {$this->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 the whole content of this article, I hope that you learn PHP programming help.

http://www.bkjia.com/PHPjc/1127902.html www.bkjia.com true http://www.bkjia.com/PHPjc/1127902.html techarticle PHP Singleton mode is what PHP implementation of the singleton mode, PHP mode one, what is a singleton mode? 1, meaning as the creation mode of the object, Singleton mode ensures that one class has only one ...

  • Related Article

    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.