PHP design mode: Singleton mode. Single-instance mode in PHP design mode: makes an object of the class a unique instance in the system. The most common use of the single-instance mode in PHP is database operations. Avoid the Singleton mode of PHP design patterns in the system
Singleton mode: Makes an object of the class a unique instance in the system.
In PHP, the most common single-instance mode is database operations. To avoid having to connect to multiple databases in the system and waste system resources, you can use the Singleton mode. Each operation on the database uses an instance.
Simple example
Class AClass {
// Used to store your own instance
Public static $ instance;
// Private constructor to prevent external instantiation of objects
Private function _ construct (){}
// Private clone function to prevent external clone objects
Private function _ clone (){}
// Static method, unified entry for single-instance access
Public static function getInstance (){
If (! (Self: $ instance instanceof self )){
Self: $ instance = new self ();
}
Return self: $ instance;
}
// Test
Public function test (){
Return "done ";
}
// Private clone function to prevent external clone objects
Private function _ clone (){}
}
Class BClass extends AClass {
}
// Obtain the instance
$ Aclass = AClass: getInstance ();
$ Bclass = BClass: getInstance ();
// Call method
Echo $ aclass-> test ();
For some large applications that may connect to multiple databases, a common object in different databases may cause problems, such as distribution of connection handles, we can change $ instance to an array and control it through different parameters.
Simple example
Class DB {
// Used to store your own instance
Public static $ instance = array ();
Public $ conn;
// Private constructor to prevent external instantiation of objects
Private function _ construct ($ host, $ username, $ password, $ dbname, $ port ){
$ This-> conn = new mysqli ($ host, $ username, $ password, $ dbname, $ port );
}
// Static method, unified entry for single-instance access
Public static function getInstance ($ host, $ username, $ password, $ dbname, $ port ){
$ Key = $ host. ":". $ port;
If (! (Self: $ instance [$ key] instanceof self )){
Self: $ instance [$ key] = new self ($ host, $ username, $ password, $ dbname, $ port); # instantiate
}
Return self: $ instance [$ key];
}
// Query
Public function query ($ ql ){
Return $ this-> conn-> query ($ SQL );
}
// Private clone function to prevent external clone objects
Private function _ clone (){}
// Release resources
Public function _ destruct (){
$ This-> conn-> close ();
}
}
Using Singleton mode: makes an object of the class a unique instance in the system. database operations are the most common use of Singleton mode in PHP. Avoid in the system...