Php design mode instance-Singleton mode-PHP Tutorial

Source: Internet
Author: User
Tags zend framework
Php design pattern instance Singleton pattern. This article introduces the Singleton mode of php design mode instances. For more information, see reference. Singleton type: 1. the constructor must be marked as private. This document does not describe how to use the Singleton mode for php design mode instances. For more information, see reference.

Singleton class:

1. the constructor must be marked as private. the singleton class cannot be instantiated in other classes and can only be instantiated by itself.
2. have a static member variable for the instance that saves the class
3. have a public static method to access this instance. [The getInstance () method is commonly used to instantiate a singleton class. the instanceof operator can detect whether the class has been instantiated]
Note: You need to create the _ clone () method to prevent objects from being copied.

Purpose:
1. php applications are mainly used for databases. Therefore, a large number of database operations exist in an application. Using the Singleton mode can avoid the resources consumed by a large number of new operations.
2. if you need a class in the system to globally control some configuration information, you can easily implement it using the Singleton mode. Refer to the ZF FrontController section.
3. summary of requests on a page for debugging. because all the code is concentrated in a class, we can set hooks in the class and output logs to avoid var_dump and echo everywhere.

Example of the php Singleton mode.

The code is as follows:


/**
* Singleton mode

*/
Class DanLi {
// Static member variable
Private static $ _ instance;
// Private constructor
Private function _ construct (){
}
// Prevent the object from being cloned
Public function _ clone (){
Trigger_error ('Clone is not allow! ', E_USER_ERROR );
}
Public static function getInstance (){
If (! (Self: $ _ instance instanceof self )){
Self: $ _ instance = new self;
}
Return self: $ _ instance;
}
Public function test (){
Echo "OK ";
}
}

// Error: $ danli = new DanLi (); $ danli_clone = clone $ danli;
// Correct: $ danli = DanLi: getInstance (); $ danli-> test ();
?>


Next we will discuss why we should use the PHP Singleton mode?

Most people understand the purpose of the Singleton model literally. they think that this is a saving of system resources and can avoid repeated instantiation. it is a kind of "family planning ". PHP clears all resources from the memory after each execution of the page. therefore, in PHP, the singleton needs to be re-instantiated every time it is run, thus losing the significance of the Singleton repeated instantiation. in this regard, the PHP Singleton is indeed a bit disappointing. but does the Singleton only have this function and application? The answer is No. let's take a look.

1. php applications mainly involve database applications. Therefore, a large number of database operations exist in an application. when using the object-oriented method for development (nonsense), if you use the Singleton mode, this avoids the resource consumption of a large number of new operations.

2. if you need a class in the system to globally control some configuration information, you can easily implement it using the Singleton mode. for details, refer to the FrontController section of zend Framework.

3. in a page request, debugging is easy, because all the code (such as database operation db) is concentrated in one class, we can set hooks in the class and output logs, this avoids var_dump and echo everywhere.

The code is as follows:

/**
* Singleton mode in design mode
* $ _ Instance must be declared as a static private variable
* Constructor and Destructor must be declared as private to prevent external programs from new
* Class, thus losing the significance of Singleton mode
* The getInstance () method must be set to public and must be called
* To return a reference to the instance
*: The operator can only access static variables and static functions.
* New objects consume memory.
* Use cases: database connections are the most common scenarios.
* After an object is generated in Singleton mode,
* This object can be used by many other objects.
*/
Class Example
{
// Save the instance in this attribute
Private static $ _ instance;

// The constructor declares private to prevent direct object creation.
Private function _ construct ()
{
Echo 'I am construceted ';
}

// Singleton method
Public static function singleton ()
{
If (! Isset (self ::$ _ instance ))
{
$ C =__ CLASS __;
Self: $ _ instance = new $ c;
}
Return self: $ _ instance;
}

// Prevents users from copying object instances
Public function _ clone ()
{
Trigger_error ('Clone is not allow', E_USER_ERROR );
}

Function test ()
{
Echo ("test ");

}
}

// This write method will fail because the constructor is declared as private.
$ Test = new Example;

// The following is a singleton object of the Example class.
$ Test = Example: singleton ();
$ Test-> test ();

// Copying an object will result in an E_USER_ERROR.
$ Test_clone = clone $ test;
?>

Bytes. Singleton class: 1. the constructor must be marked as private. the singleton class is not...

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.