Php design pattern instance Singleton pattern

Source: Internet
Author: User
This article introduces the Singleton mode method of php design mode instances. if you need to know more, refer to the reference singleton class: 1. the constructor needs to be marked as private, the singleton class cannot be any other

This article introduces the Singleton mode of 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. there is a public static method to access this instance. [the getInstance () method is commonly used to instantiate the singleton class, and the instanceof operator can be used to 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 certain configuration information, you can use the Singleton mode for convenient implementation. refer to the FrontController section of ZF.

3. summary of requests on a page for debugging. because all the code is concentrated in a class, we can set hooks and output logs in the class to avoid var_dump and echo everywhere.

Example of the php Singleton mode.

The instance code is as follows:

  1. /**
  2. * Singleton mode
  3. */
  4. Class DanLi {
  5. // Static member variable
  6. Private static $ _ instance;
  7. // Private constructor
  8. Private function _ construct (){
  9. }
  10. // Prevent the object from being cloned
  11. Public function _ clone (){
  12. Trigger_error ('Clone is not allow! ', E_USER_ERROR );
  13. }
  14. Public static function getInstance (){
  15. If (! (Self: $ _ instance instanceof self )){
  16. Self: $ _ instance = new self;
  17. }
  18. Return self: $ _ instance;
  19. }
  20. Public function test (){
  21. Echo "OK ";
  22. }
  23. }
  24. // Error: $ danli = new DanLi (); $ danli_clone = clone $ danli;
  25. // Correct: $ danli = DanLi: getInstance (); $ danli-> test ();
  26. ?>

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 instance code is as follows:

  1. /**
  2. * Singleton mode in design mode
  3. * $ _ Instance must be declared as a static private variable
  4. * Constructor and Destructor must be declared as private to prevent external programs from new
  5. * Class, thus losing the significance of Singleton mode
  6. * The getInstance () method must be set to public and must be called
  7. * To return a reference to the instance
  8. *: The operator can only access static variables and static functions.
  9. * New objects consume memory.
  10. * Use cases: database connections are the most common scenarios.
  11. * After an object is generated in Singleton mode,
  12. * This object can be used by many other objects.
  13. */
  14. Class Example
  15. {
  16. // Save the instance in this attribute
  17. Private static $ _ instance;
  18. // The constructor declares private to prevent direct object creation.
  19. Private function _ construct ()
  20. {
  21. Echo 'I am construceted ';
  22. }
  23. // Singleton method
  24. Public static function singleton ()
  25. {
  26. If (! Isset (self ::$ _ instance ))
  27. {
  28. $ C =__ CLASS __;
  29. Self: $ _ instance = new $ c;
  30. }
  31. Return self: $ _ instance;
  32. }
  33. // Prevents users from copying object instances
  34. Public function _ clone ()
  35. {
  36. Trigger_error ('Clone is not allow', E_USER_ERROR );
  37. }
  38. Function test ()
  39. {
  40. Echo ("test ");
  41. }
  42. }
  43. // This write method will fail because the constructor is declared as private.
  44. $ Test = new Example;
  45. // The following is a singleton object of the Example class.
  46. $ Test = Example: singleton ();
  47. $ Test-> test ();
  48. // Copying an object will result in an E_USER_ERROR.
  49. $ Test_clone = clone $ test;
  50. ?>

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.