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 ()
{
}//Overlay __clone () method, prohibit 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?
Most people understand its purpose from the literal meaning of the singleton pattern, which is a kind of "family planning", which is to save the resources of the system, to avoid the repetition of the instantiation. And every time PHP finishes the page, it clears all the resources out of memory. As a result, the single example of PHP in the actual operation of each run is to be instantiated, so that the single example of repeated instantiation of the meaning of. In this respect alone, PHP's single example is a bit disappointing to everyone. But is the single example just this function and application? The answer is no, let's look at it together.
PHP is mainly used in database applications, so an application will have a large number of database operations, in the use of object-oriented approach to development (nonsense), if the use of single case mode, you can avoid a large number of new operations to consume resources.
If you need a class in your system to control some configuration information globally, it is convenient to use a single example pattern. This can be referred to the Frontcontroller section of the Zend Framework.
In a page request, it is easy to debug, because all the code (such as database Operation class DB) is concentrated in a class, we can set the hook in the class, output log, so as to avoid everywhere var_dump, echo.
1, PHP disadvantage:
The PHP language is an interpreted scripting language that enables each PHP page to be interpreted and executed All related resources will be 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 applications:
(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 a single case mode can avoid a lot 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 globally control some configuration information, then a single case pattern can be easily implemented.
Three, how do I implement a single case pattern?
1, normal database access example:
<?php ...
Initializes a database handle
$db = new db (...);
//Add user Information
$db->adduserinfo (...);
......
//To access the database in the function, 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 () {}; //Overlay __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 (...); ?>
The following code is an encapsulation of the PDO operation database class, taking a single case 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->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 ()); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} } /** * 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; &NBSP;&NBSP;&NBSP;&NBSP} /** * Query 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 &NBSP;&NBSP;&NBSP;&NBSP} /** * Update update * * @param string
$table table name * @param Array $arrayDataValue fields and values *&nBSP @param String $where conditions * @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 '"; &NBSP} $strSql = substr ($
STRSQL,&NBSP;1); $strSql = "update ' $
Table ' SET $strSql WHERE $where '; } else { $strSql = "replace into ' $table ' ". Implode (', '), array_keys ($arrayDataValue)). "
') VALUES (' "Implode (" ', ' ", $arrayDataValue)." &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} if ($
debug === true) $this->debug ($STRSQL);
$result = $this->dbh->exec ($STRSQL);
$this->getpdoerror (); return&nbSP; $result; &NBSP;&NBSP;&NBSP;&NBSP} /** * Insert Insert * * @param string
$table table name * @param Array $arrayDataValue fields and values * @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; &NBSP;&NBSP;&NBSP;&NBSP} /** * Replace Overlay Insert * * @param string $table Table name * @param Array $arrayDataValue Fields and Values * @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; &NBSP;&NBSP;&NBSP;&NBSP} /** * Delete 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; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} } /** * execSql Execute SQL statements * * @param String $strSql * @param
Boolean $debug * @return int */ public function execsql ($strSql, $debug = false) { if ($debug === true) $this-
>debug ($STRSQL);
$result = $this->dbh->exec ($STRSQL);
$this->getpdoerror (); return $result; &NBSP;&NBSP;&NBSP;&NBSP} /** * Get field maximum * * @param string $table table name * @param string $field _name field name * @param string $where conditions */ 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&nbSP; ($debug === true) $this->debug ($STRSQL);
$arrTemp = $this->query ($strSql, ' Row ');
$maxValue = $arrTemp ["Max_value"]; if ($maxValue == " | | $maxValue == null) {
$maxValue = 0; } return $
MaxValue; &NBSP;&NBSP;&NBSP;&NBSP} /** * 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, $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 ']; &NBSP;&NBSP;&NBSP;&NBSP} /** * Get tablesEngine * * @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 name= '". $tableName. "'";
$arrayTableInfo = $this->query ($STRSQL);
$this->getpdoerror ();
return $arrayTableInfo [0][' Engine ']; &NBSP;&NBSP;&NBSP;&NBSP} /** * begintransaction Transaction Start */ private Function begintransaction () { $
This->dbh->begintransaction (); &NBSP;&NBSP;&NBSP;&NBSP} /** * commit Transaction Submission */ private function
Commit () { $this->dbh->commit (); &NBSP;&NBSP;&NBSP;&NBSP} /** * rollback transaction rollback */ private function Rollback () { $this->dbh->rollback (
); &NBSP;&NBSP;&NBSP;&NBSP} /** &Nbsp; * transaction multiple SQL statements through transactions * Before calling, it is necessary to determine whether the table engine supports transactions * * @param by Gettableengine array $arraySql * @return boolean
*/ public function exectransaction ($ARRAYSQL) {
$retval = 1;
$this->begintransaction (); foreach ($arraySql as $strSql) { if ($this->execsql ($STRSQL) ==
0) $retval = 0; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} 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 $arrayField */ 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"); } &NBSP;&NBSP} } /** * getFields get 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 &NBSP;&NBSP;&NBSP;&NBSP} /** * getPDOError capture PDO error message */ private function getpdoerror () { if ($this->dbh->errorcode () != ' 00000 ') {
$arrayError = $this->dbh->errorinfo ();
$this->outputerror ($arrayError [2]); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} } /** * 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); &NBSP;&NBSP;&NBSP;&NBSP} /** * destruct Close Database connection */ public function Destruct () { $this->dbh =
Null &NBSP;&NBSP;&NBSP;&NBSP}}?>
Call Method:
<?php
require ' MyPDO.class.php ';
$db = mypdo::getinstance (' localhost ', ' root ', ' 123456 ', ' Test ', ' UTF8 ');
$db->query ("SELECT COUNT (*) Frome table");
$db->destruct ();
? >