PHP design Pattern: Learning notes in single case mode

Source: Internet
Author: User
Tags php language php class access database


Bloggers have recently begun to learn about the various design patterns of PHP. In the beginning, of course, from some simple design patterns began to learn, such as the previously published factory model, today's simple mode, and then to see the registration mode. In fact, these are the basis of the design pattern, some simple examples can be seen, for a slightly more complex examples, a little thought to go in can also understand. But the point is that it's not enough to know what it is, but how to get it to work better in the project and increase proficiency in practice. Well, let's talk about the single example we're going to see today.

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 that holds a unique instance of the class is required.
(2) Constructors and cloning functions must be declared private to prevent the external program new class from losing the meaning of the single case schema.
(3) A public static method (usually the GetInstance method) that accesses this instance must be provided to return a reference to a unique instance.
Suppose we need to design a database access class at the moment, we need to use a single example pattern, and look at the following example:

<?php class db {    private $_db;     private 
static $_instance;     private function __construct (...)     {          $this->_db = pg_connect (...); /postgrsql    &nbsp}     private function __clone ()  {}; 
 //overrides the __clone () method to prohibit cloning of     public static function getinstance ()  {         if (!) ( self::$_instance instanceof self)  )  {        
    self::$_instance = new self ();         }         return 
Self::$_instance; &NBSP;&NBSP;&NBSP;&NBSP}     public function sql (...)  {        /*          * code          */   &nbsp}} $db  = db:: getinstance ();   $db->sql (); ?>

<111?111php111

/1**

* Design pattern of 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 thus loses the meaning of a single case pattern

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

* To return a reference to an instance

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

* New object will consume memory

* Use the scene: The most common place is the database connection.

* After an object is generated using a single case pattern,

* This object can be used by many other objects.

*/

Class Danli {



To save a static member variable for a class instance

private static $_instance;



The construction method of private tag

Private Function __construct () {

Echo ' is a constructed method; ';

}



Create a __clone method to prevent an object from replicating a clone

Public Function __clone () {

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

}



A singleton method, which is used to access the public static method of 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 that instantiates the private tag constructor with new will complain

$danli = new Danli ();



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

$danli = Danli::getinstance ();

$danli->test ();



The copy (clone) object will cause a E_user_error

$danli _clone = Clone $danli;

Example 3

1, the ordinary database access examples:

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

}

?>


Example 4: Use a single case pattern to manipulate 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 (...)        {                & nbsp;  }           public function getuserinfo ( ...)        {           }      }     //TEST&NBSP;&NBsp    $db  = db::getinstance ();      $db->adduserinfo (...);       $db->getuserinfo (...);         ?>

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.

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.