PHP Singleton mode summary tutorial

Source: Internet
Author: User
In the past, we have talked about the understanding of the single-instance mode of the php single-state design mode and the Common Application scenarios of the Singleton mode. now we will summarize the previous scenarios. In Singleton mode, only one instance exists for an object and a full... in the past, we have talked about the understanding of the single-instance mode of the php single-state design mode and the Common Application scenarios of the Singleton mode. now we will summarize the previous scenarios.

In Singleton mode, a global access point (usually a static getInstance method) is provided for the unique instance to keep an object only in one instance ), the Singleton mode is widely used, for example:

Database operation object, log writing object, global configuration parsing object, etc.

The common feature of these scenarios is that, in terms of business logic, changing an object during runtime only requires one instance and multiple new instances will increase unnecessary resource consumption and facilitate global calls. The following three aspects are described respectively:

1. only one instance is required for the business

Take the database connection object as an example. if you join a shopping website with a MySQL database 127.0.0.1: 3306, no matter how many database modification operations we need in a process, you only need to connect to the database once and use the same database Connection handle (MySQL Connection Resource). from the business needs, you only need one instance.

On the contrary, taking shopping websites as an example, there are many products that are different (id, name, price ..), in this case, you need to display a Product list and add a Product as the data ing object. Therefore, an instance cannot meet the business needs because each Product is different.

2. keep new operations to increase unnecessary resource consumption

We usually perform some business operations in the class constructor (the new operation will certainly be called, for example, the database connection object may try to read the database configuration in the constructor and connect to the database (for example, mysqli ::__ construct ()) the log writing object determines whether the log writing directory exists and is written (the directory may not be created or changed), and the global configuration parsing object may need to locate the storage directory of the configuration file and perform file scanning.

These services consume considerable resources. if we need to do this once in a process, it will be very helpful for us to improve the running efficiency of the application.

3. convenient global call

Because one of the major features of the Singleton mode is to obtain the object instance through the static method, it means that when accessing the object method, you do not need to first create an object instance. if you need to change the object, you need to use it in many places, this improves the convenience of calling.

The code is as follows:

Class Logger {// first, a private static variable is required to store the generated object instance private static $ instance; // business variable, saving the log write path private $ logDir; // Constructor. Note that the constructor must be private and cannot be instantiated externally (new externally). private function _ construct () {// debug the output, echo "new Logger instance rn"; $ logDir = sys_get_temp_dir (). DIRECTORY_SEPARATOR. "logs"; if (! Is_dir ($ logDir) |! File_exists ($ logDir) {@ mkdir ($ logDir) ;}$ this-> logDir = $ logDir ;}// global access point of a unique instance of the class, used to determine and return the object instance for external calls of public static function getInstance () {if (is_null (self: $ instance) {$ class =__ CLASS __; // Obtain the object type. you can also use the new self () method self: $ instance = new $ class ();} return self: $ instance ;} // reload the _ clone () method. the object is Not allowed to clone public function _ clone () {throw new Exception ("Singleton Class Can Not Be Cloned ");} // specific business method. There are many methods actually available: public function logError ($ message) {$ logFile = $ this-> logDir. DIRECTORY_SEPARATOR. "error. log "; error_log ($ message, 3, $ logFile) ;}// log call $ logger = Logger: getInstance (); $ logger-> logError ("An error occured"); $ logger-> logError ("Another error occured"); // or call Logger: getInstance () -> logError ("Still have error"); Logger: getInstance ()-> logError ("I shocould fix it ");

In Singleton mode, you may encounter a special situation, such as database connection objects. for large applications, you may need to connect to multiple databases, therefore, an object shared by different databases may cause problems, such as connection allocation, insert_id acquisition, and last_error. This problem is also well solved by converting our $ instance variable into an associated array, pass different parameters to the getInstance method to get different "singleton objects" (the meaning of the quotation marks is: Strictly speaking, the class may be new multiple times, but this new is under our control, rather than outside the class), the code is as follows:

Class MysqlServer {// note that it is changed to the plural value. of course, it is only for identification. private static $ instances = array (); // business variable, keep the mysqli object private $ conn of the current instance; // notable feature: private constructor to avoid private function _ construct ($ host, $ username, $ password, $ dbname, $ port) {$ this-> conn = new mysqli ($ host, $ username, $ password, $ dbname, $ port );} // public static function getInstance ($ host = 'localhost', $ username = 'root', $ password = '123 ', $ dbname = 'mydb', $ port = '000000') {$ key = "{$ host }:{ $ port }:{ $ username }:{ $ dbname }"; if (emptyempty (self: $ instances [$ key]) {// you can use the new self (); method $ class =__ CLASS __; self :: $ instances [$ key] = new $ class ($ host, $ username, $ password, $ dbname, $ port);} return self ::$ instances [$ key];} // overload the _ clone method. object instances cannot Be Cloned. public function _ clone () {throw new Exception ("Singleton Class Can Not Be Cloned ");} // query the business method. other business methods are omitted later. public function query ($ SQL) {return $ this-> conn-> query ($ SQL );} // release The Resource public function _ destruct () {$ this-> conn-> close () ;}} as soon as possible ();}}

Question 1:Can a singleton class have sub-classes? because the constructor of Singleton classes is private, they cannot be inherited. to inherit, you must change the constructor to protected or public, this violates the intention of the Singleton mode. Therefore, if you want to add a subclass to a singleton class, you need to think about whether the pattern is incorrect or there is a problem with the structure design.

Question 2:The Singleton abuse mode is relatively easy to understand and implement. Therefore, once you realize the benefits of Singleton mode, you may want to write all classes into Singleton, therefore, before using the secondary mode, you must consider the above three cases to see if they are really necessary.


Tutorial URL:

You are welcome to add your _ favorites to the Favorites folder, but please keep the link for this article.

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.