PHP implements a database class ____php with a single case pattern

Source: Internet
Author: User
Tags php language pconnect

The starting point for using the single case pattern:

1, the application of PHP is mainly in the database application, so an application will have a large number of database operations, the use of single case mode, you can avoid a large number of new operations to consume resources.

2, if the system needs to have a class to global control of some configuration information, then the use of a single example mode can be easily implemented. This can be reviewed in the Frontcontroller part of ZF.

3, in a page request, easy to debug, because all the code (such as database Operation class DB) are concentrated in a class, we can set the hook in the class, output log, so as to avoid everywhere var_dump, echo.

Create an individual note:

1, a ray can only have one class object (only one object can be instantiated)

2. It must create this instance itself

3. It must provide this example to the whole system.

4. Constructors and cloning functions must be declared private, in order to prevent the external program new class from losing the meaning of a single case pattern

5. The getinstance () method must be declared as public, and this method must be called to return a reference to a unique instance

6. Have a static member variable that holds an instance of the class

7, the single case of PHP mode is relatively, because the PHP interpretation of the operating mechanism so that each PHP page is interpreted and implemented, all the relevant resources will be recycled

8, has a public access to this instance of the static method (commonly used getinstance () method to instantiate a singleton class, through the instanceof operator can detect whether the class has been instantiated)

In addition, you need to create a __clone () method to prevent objects from being replicated (clones)

The code is as follows:

1 <?php
 2 class Danli
 3 {
 4 
 5//Save class Instance static member variable
 6     private static $_instance;
 7 
 8//private Mark Construction method
 9     Private Function __construct ()     {         echo ' This is a constructed method; '; 
14//Create __clone method to prevent object from being replicated clone public     function __clone ()     {
17         Trigger_error (' Clone is not allow! ', e_user_error); 
20//A singleton method for accessing the public static method of the instance     getinstance ()         if (!) ( Self::$_instance instanceof Self)) {             self::$_instance = new Self;         self::$_instance return         ;
The     public     function test ()     {         echo ' invokes method success '; 
36/* The class that instantiates the private tag constructor with new will have an error of
$danli = new Danli (); 
39 Copy (clone) object will cause a e_user_error
$danli _clone = Clone $danli; 
44//correct method, using double colon:: operator access static method to get instance
$danli = Danli::getinstance ();
$danli->test ();
?>

Implement a database class using a single case pattern:

 1 <?php 2 class DBHelper 3 {4 private $link;
 5 static private $_instance; 6 7//Connection Database 8 Private Function __construct ($host, $username, $password) 9 {$this->link = m
Ysql_connect ($host, $username, $password);
One $this->query ("SET NAMES ' UTF8 '", $this->link); //echo Mysql_errno ($this->link). ": " . Mysql_error ($link).
"N";
//var_dump ($this->link);
return $this->link; The Private Function __clone () is public static function Get_class_nmdb ($host, $username 
, $password) {//$connector = new Nmdb ($host, $username, $password);//return $connector 23 The IF (FALSE = = self::$_instance instanceof self)) {self::$_instance = new self ($host, $username
, $password);
Self::$_instance return; 28} 29//Connection Data Sheet Public Function select_db ($database) $this-&GT;result = mysql_select_db ($database);
$this->result; 34} 35//Execute SQL statement the Public Function query ($query) is {return $this->result = mysql_query (
$query, $this->link); 39} 40//Save the result set as an array of the public function Fetch_array ($fetch _array) of the $this->result
= Mysql_fetch_array ($fetch _array, MYSQL_ASSOC); 44} 45//record number of public function num_rows ($query) $this->result = mysql_num_
Rows ($query); 49} 50//Close database connection The->result = Mysql_close ($this-
>link);
$connector = Dbhelper::get_class_nmdb ($host, $username, $password);
$connector-> select_db ($database); ?>

The

can also refer to this class implementation:

 1 <?php 2/* 3 * mysql single case 4 * * 5 class mysql{6 private $host = ' localhost ';//Database host 7 private $user = ' root '; Database username 8 Private $pwd = '; Database user name password 9 private $database = ' Imoro_imoro '; Database name is private $charset = ' UTF8 ';             Database coding, gbk,utf8,gb2312 private $link;
database connection identification;             Private $rows; The query gets a multiline array of static $_instance;         Storage Object 14/** 15 * Constructor 16 * Private __construct ($pconnect = false) {19 if (! $pconnect) {$this->link = @ mysql_connect ($this->host, $this->user, $this->pwd) or $th
Is->err (); } else {$this->link = @ mysql_pconnect ($this->host, $this->user, $this->pwd) or $th
Is->err ();
mysql_select_db ($this->database) or $this->err ();
$this->query ("SET NAMES ' {$this->charset} '", $this->link);
$this->link;  27   28/** 29 * Prevention of being cloned */* Private Function __clone () {} to public static function get  Instance ($pconnect = False) {(= (false = = Self::$_instance instanceof self)) {self::$_instance =
New self ($pconnect);
Panax Notoginseng return self::$_instance;  38} 39/** 40 * Query/"Public function query ($sql, $link =") {$this->result =
mysql_query ($sql, $this->link) or $this->err ($sql);
$this->result; 45} 46/** 47 * Single line record/Public function GetRow ($sql, $type = Mysql_assoc) {$resul
t = $this->query ($sql);
Mysql_fetch_array ($result, $type); 52} 53/** 54 * Multiple Line Records public function getRows ($sql, $type = Mysql_assoc) {MB $resu
lt = $this->query ($sql);        while ($row = @ mysql_fetch_array ($result, $type)) {$this->rows[] = $row; 60 $this->rows;         62} 63/** 64 * error message Output/protected function err ($sql = null) {67//Here output error message 68
echo ' ERROR ';
The exit ();
70} 71} 72//use case $db = Mysql::getinstance ();
$db 2 = mysql::getinstance ();
$data = $db->getrows (' select * from blog ');
//print_r ($data); 77//To determine whether two objects are equal if ($db = = = $db 2) {?> echo ' true ';

Disadvantages of the PHP single example pattern
As we all know, the PHP language is an interpreted scripting language, which 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 and other types of compilation, such as in Java, a single meeting has been in the entire application lifecycle, variable is across the page level

, the uniqueness of this instance in the life cycle of the application can be truly achieved. In PHP, however, all variables, whether

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.