PHP design pattern: Singleton mode

Source: Internet
Author: User
Tags pconnect

PHP design pattern: Singleton moderesolve multiple Duplicate request issues

Some days ago began to really understand the design pattern, to start, simply from the singleton mode, of course, read some of the information on the web, a better understanding of the singleton model, look at the introduction, and then look at the code basic also can understand, design patterns these flower point of mind Basic is able to understand, Of course, to be good use of the project is also a need for a certain practice, not just know, or is very strong and understand, one to the actual operation will not be, nonsense will not say more, The comrades on the front of the PHP refueling it;

Singleton mode (duty mode):

Simply put, an object (before learning design patterns, need to understand the object-oriented thinking) is only responsible for a specific task;

Singleton class:

1. Theconstructor needs to be marked as private(access control: Prevent external code from creating objects using the new operator), the Singleton class cannot be instantiated in other classes, and can only be instantiated by itself;

2.have a static member variable that holds an instance of the class

3, has a public access to this instance of the static method (common getinstance () method to instantiate a singleton class, through the instanceof Operator can detect if the class has been instantiated)

In addition, you need to create a __clone () method to prevent the object from being copied (cloned)

Why use PHP singleton mode?

1, the application of PHP is mainly in the database application , so there will be a large number of database operations in an application , using a singleton mode , you can avoid a large number of The resource consumed by the new operation.

2, if the system needs to have a class to control some of the configuration information globally , then using the singleton mode can be easily implemented . This can be see ZF's Frontcontroller part.

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 hooks in the class , output the log, thus avoiding var_dump everywhere , Echo.

Code implementation:

<111?111php111

/1**

* Design pattern of a single case mode

* $_instance must be declared as a static private variable

* Constructors and destructors must be declared private to prevent external program new

* Class to lose the meaning of the singleton pattern

* The getinstance () method must be set to public, this method must be called

* To return a reference to the instance

*:: operator can only access static variables and static functions

* New objects will consume memory

* Usage Scenario: The most common place is the database connection.

* Once an object is generated using singleton mode,

* This object can be used by many other objects.

*/

Class Danli {

To save a static member variable for a class instance

private static $_instance;

How to construct private tags

Private Function __construct () {

Echo ' This is a constructed method;

}

To create a __clone method to prevent an object from being cloned

Public Function __clone () {

Trigger_error (' Clone is not allow! ', e_user_error);

}

A singleton method, a public static method for accessing an instance

public static function getinstance () {

if (! ( Self::$_instance instanceof Self)) {

Self::$_instance = new Self;

}

return self::$_instance;

}

Public Function test () {

Echo ' Invoke method succeeded ';

}

}

Class with new instantiation of private tag constructor will error

$danli = new Danli ();

Correct method, use double colon:: operator to access the static method to get the instance

$danli = Danli::getinstance ();

$danli->test ();

Copying (cloning) an object will result in a e_user_error

$danli _clone = Clone $danli;

Do your own:

Class Dbmysql {
var $querynum = 0;
var $link;

Static variables Save Global instances
private static $_instance = null;
static method, single access portal
static public Function getinstance ($con _db_host, $con _db_id, $con _db_pass, $con _db_name) {
if (Is_null (self::$_instance) | | isset (self::$_instance)) {
Self::$_instance = new self ($con _db_host, $con _db_id, $con _db_pass, $con _db_name);
}
return self::$_instance;
}

function __construct ($con _db_host, $con _db_id, $con _db_pass, $con _db_name = ", $db _charset= ' utf8 ', $pconnect = 0) {
if ($pconnect) {
if (! $this->link = @mysql_pconnect ($con _db_host, $con _db_id, $con _db_pass)) {
$this->halt (' Can not connect to MySQL server ');
}
} else {
if (! $this->link = @mysql_connect ($con _db_host, $con _db_id, $con _db_pass, 1)) {
$this->halt (' Can not connect to MySQL server ');
}
}
if ($this->version () > ' 4.1 ') {
if ($db _charset!= ' latin1 ') {
@mysql_query ("SET character_set_connection= $db _charset, character_set_results= $db _charset, character_set_client= Binary ", $this->link);
}

if ($this->version () > ' 5.0.1 ') {
@mysql_query ("SET sql_mode=", $this->link);
}
}

if ($con _db_name) {
@mysql_select_db ($con _db_name, $this->link);
}

}

}

Connection:

$db =dbmysql::getinstance ($con _db_host, $con _db_id, $con _db_pass, $con _db_name);
$rs = $db->query (' select * from H_member ');

PHP design pattern: Singleton mode

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.