Analysis of advantages of PHP single-case model

Source: Internet
Author: User
Tags dsn php language php class zend framework
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 ');  }   Private Function __clone ()  {  }//overrides __clone () method, prevents cloning



(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?

Most people understand its purpose from the literal meaning of the singleton pattern, and think that it is a kind of "family planning" that saves the system resources and avoids duplication of instantiation. Each time PHP executes the page, it cleans up all the resources from memory. Thus, in PHP, the single instance of the actual operation needs to be re-instantiated, thus losing the meaning of a single case of repeated instantiation. In this respect alone, PHP's singleton is indeed a bit disappointing for you. But does the singleton only have this function and application? The answer is no, let's take a look.

The main application of PHP is the database application, so there will be a large number of database operations in an application, in the use of object-oriented development (nonsense), if the use of Singleton mode, you can avoid a large number of new operations to consume resources.
If a class is needed in the system to control some configuration information globally, it can be easily implemented using singleton mode. This can be see the Frontcontroller section of the Zend Framework.
In one 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 hooks in the class, output the log, so as to avoid var_dump everywhere, echo. 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 ...  Initializes 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 () {};  Override the __clone () method to disallow 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 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->DBH = new PDO ($this->dsn, $dbUser, $DBPASSWD);

$this->dbh->exec (' SET character_set_connection= '. $dbCharset. ', character_set_results= '. $dbCharset. ', Character_set_client=binary ');

} <a href= "\"/tags.php/catch/\ "" target= "\" _blank\ "" >catch</a> (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 queries

*

* @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) {

$recordset->setfetchmode (PDO::FETCH_ASSOC);

if ($queryMode = = ' All ') {

$result = $recordset->fetchall ();

} elseif ($queryMode = = ' Row ') {

$result = $recordset->fetch ();

}

} else {

$result = null;

}

return $result;

}

/**

* Update Updates

*

* @param String $table table name

* @param Array $arrayDataValue fields and values

* @param String $where condition

* @param Boolean $debug

* @return Int

*/

Public Function Update ($table, $arrayDataValue, $where = ", $debug = False)

{

$this->checkfields ($table, $arrayDataValue);

if ($where) {

$STRSQL = ";

<a href= "\"/tags.php/foreach/\ "" target= "\" _blank\ "" >foreach</a> ($arrayDataValue as $key = = $value) {

$strSql. = ", ' $key ' = ' $value '";

}

$STRSQL = <a href= "\"/tags.php/substr/\ "" target= "\" _blank\ "" >substr</a> ($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 Insertion

*

* @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;

}

/**

* Replace Overwrite mode 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;

}

/**

* Delete deletion

*

* @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

*/

Public Function Execsql ($STRSQL, $debug = False)

{

if ($debug = = = True) $this->debug ($STRSQL);

$result = $this->dbh->exec ($STRSQL);

$this->getpdoerror ();

return $result;

}

/**

* Get field Maximum value

*

* @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 '];

}

/**

* Get 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 name= '". $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 multiple SQL statements with transactions

* Before calling to determine whether the table engine supports transactions through Gettableengine

*

* @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 checks 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.");

}

}

}

/**

* 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 messages

*/

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 Exception (' MySQL Error: '. $strErrMsg);

}

/**

* Destruct Close database connection

*/

Public Function Destruct ()

{

$this->DBH = null;

}

}

?>



Call Method:

1

2

3

4

5

6

<?php

require ' MyPDO.class.php ';

$db = mypdo::getinstance (' localhost ', ' root ', ' 123456 ', ' Test ', ' UTF8 ');

$db->query ("<a href=" \ "/tags.php/select/\" "target=" \ "_blank\" ">select</a> count (*) Frome table") ;

$db->destruct ();

?

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.