PHP Single case mode is what PHP implements a singleton mode _php instance

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

One, what is a single case mode?
1, meaning
as an object's creation pattern, the singleton pattern ensures that a class has only one instance, and instantiates it and provides it globally to the entire system. Instead of creating an instance copy, it returns a reference to an instance stored within a singleton class.
2, the single example mode of the three points:
(1). A static member variable is required to hold a unique instance of the class:
private static $_instance;
(2). Constructors and cloning functions must be declared private to prevent the external program new class from losing the meaning of a single case pattern:

Private Function __construct ()  
{  
  $this->_db = Pg_connect (' xxxx '); 
}  
Private Function __clone () 
{ 
}//overrides __clone () method to disable cloning 

(3). A public static method (usually the GetInstance method) that accesses this instance must be provided to return a reference to a unique instance

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

Second, why use the single case mode?
1, PHP Disadvantages:

The PHP language is an interpreted scripting language that enables each PHP page to be interpreted and executed, and all related resources are recycled. In other words, PHP does not have the language level to make an object resident memory, which is different from ASP.net, Java, such as a single meeting in Java throughout the lifecycle of the application, variables are across the page level, The uniqueness of this instance in the life cycle of the application is truly achievable. 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 created, will be emptied after the completion of the page, so it seems that the PHP single example mode has no meaning, So PHP Single example mode I think it makes sense to only have multiple scenarios when it comes to a single page-level request and need to share the same object resource.

2, single case mode in PHP application occasions:
(1), Application and database interaction
An application will have a large number of database operations, such as the database handle to connect to the database, the use of single case mode can avoid a large number of new operations, because each new operation consumes memory resources and system resources.
(2), control configuration information
If you need a class in your system to control some configuration information globally, it is convenient to use a single example pattern.

How to realize the single case mode?
1, the ordinary database access examples:

<?php ... 
Initializes 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 (...); /again new database class, and database to establish a connection 
  $db = query (...); /Access database based on query statement 
} 
 

2, the application of a single example mode to operate the database:

<?php 
class DB  
{  
  private $_db;  
  private static $_instance;  
  
  Private function __construct (...)  
  {  
    $this->_db = Pg_connect (...); /postgrsql  
  }  
  
  Private Function __clone () {};//overwrite __clone () method, prohibit clone 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 is an encapsulation of the PDO operations database class, taking a single case pattern:

<?php/** * Mypdo/class Mypdo {protected static $_instance = NULL;
  protected $dbName = ';
  protected $dsn;
  
  protected $DBH; /** * Structure * * @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 ');
    The catch (Pdoexception $e) {$this->outputerror ($e->getmessage ()); }/** * Prevent cloning * */Private Function __clone () {}/** * Singleton instance * * @return O Bject */public static function getinstance ($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset) {if self::$_ins
    Tance = = null) {self::$_instance = new self ($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
   } return self::$_instance; /** * Query * @param string $STRSQL SQL statement * @param string $queryMode query (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) {$recordset->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 table name * @param Array $arrayDataValue field and value * @param string $whe Re condition * @param Boolean $debug * @return Int */Public Function update ($table, $arrayDataValue, $where = ', $de Bug = 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)). "
    ' ". 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 $de Bug * @return Int */Public Function Insert ($table, $arrayDataValue, $debug = False) {$this->checkfields
    ($table, $arrayDataValue); $STRSQL = "INSERT into ' $table '". Implode (', ', Array_keys ($arrayDataValue)). "
    ". Implode (" ', ' ", $arrayDataValue)." if ($debug = = true) $this->Debug ($STRSQL);
    $result = $this->dbh->exec ($STRSQL);
    $this->getpdoerror ();
  return $result; /** * Replace Overlay Insert * * @param String $table table name * @param Array $arrayDataValue field and value * @param Boolea N $debug * @return Int */Public function replace ($table, $arrayDataValue, $debug = False) {$this->check
    Fields ($table, $arrayDataValue); $STRSQL = "REPLACE into ' $table ' ('". Implode (', ', Array_keys ($arrayDataValue)). "
    ". Implode (" ', ' ", $arrayDataValue)."
    if ($debug = = True) $this->debug ($STRSQL);
    $result = $this->dbh->exec ($STRSQL);
    $this->getpdoerror ();
  return $result; /** * Delete * @param string $table 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; }/** * Execsql Execute SQL statement * * @param String $STRSQL * @param Boolean $debug * @return Int */PU
    Blic function Execsql ($strSql, $debug = False) {if ($debug = = True) $this->debug ($STRSQL);
    $result = $this->dbh->exec ($STRSQL);
    $this->getpdoerror ();
  return $result; 
   /** * Get Field Max * * @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 ('. $fi Eld_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 * @pa
    RAM 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 '];  /** * Get 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 $dbN
    Ame WHERE name= ' ". $tableName." ' ";
    $arrayTableInfo = $this->query ($STRSQL);
    $this->getpdoerror ();
  return $arrayTableInfo [0][' Engine ']; /** * BeginTransaction Transaction started * * PRivate function BeginTransaction () {$this->dbh->begintransaction ();
  /** * COMMIT TRANSACTION commits/private function commit () {$this->dbh->commit ();
  /** * ROLLBACK TRANSACTION rollback */Private Function rollback () {$this->dbh->rollback (); /** * Transaction A transaction processing multiple SQL statements * before calling through the Gettableengine to determine whether the table engine supports transactions * * @param array $ARRAYSQL * @retu
    RN 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 checks whether the specified field exists in the specified datasheet * * @param String $table * @param array $arrayField/privat
    e function Checkfields ($table, $arrayFields) {$fields = $this->getfields ($table); foreach ($arrayFieldsAs $key => $value) {if (!in_array ($key, $fields)) {$this->outputerror ("Unknown column ' $key ' in Fiel
  
  D list. ");}} /** * GetFields gets all the field names in the specified datasheet * * @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 capture 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 errorInformation * @param String $STRERRMSG/Private Function Outputerror ($STRERRMSG) {throw new Exception (' MySQL
  Error: '. $strErrMsg);
  /** * Destruct Close the database connection/Public function destruct () {$this->dbh = null;
 }}?>

Call Method:

<?php
require ' MyPDO.class.php ';
$db = mypdo::getinstance (' localhost ', ' root ', ' 123456 ', ' Test ', ' UTF8 ');
$db->query ("SELECT COUNT (*) Frome table");
$db->destruct ();
? >

The above is the entire content of this article, I hope that you learn PHP programming help.

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.