Design patterns are just for Java? architects - at least that's what you may have always thought. In fact, design patterns are useful for everyone. If these tools are not the preserve of “architectural astronauts,” then what are they? Why they are useful in PHP applications.
Today we will learn the singleton pattern together:
To learn a pattern, we must know the application scenarios. Otherwise, it would be like learning a martial arts move. If you don't know under what circumstances to use it, wouldn't it be a waste of effort?
For singleton mode, one of the most common applications is database connection. If every time a web page is opened, a link is created, then this consumption is a huge waste. So we need to use singleton mode to ensure that the system only establishes new connections when necessary.
If you use pseudocode to describe the singleton pattern, you can write it like this:
if(connection exists){
Return to this link
}else{
Create a new link
} }
But there is obviously a problem with this implementation. How can this link be saved so that it can be accessed externally and at the same time prevent it from being destroyed by the outside world. If this is implemented using php, it is very easy. Let’s take a look at a piece of code:
//get data class class DB { private $_db; private static $_instance; private function __construct(){ $DSN = '../../content/xxtebook.db'; $this->_db = new PDO('sqlite:'.$DSN); } //初始化数据库连接 public static function initDB(){ if(! (self::$_instance instanceof self)){ self::$_instance = new self(); } return self::$_instance; } //其它方法 }
Why should the constructor be privatized? This is a very good question, and everyone is welcome to ask such questions.
First of all, as a singleton, it is to avoid accidental creation of new instances from the outside. This can be ensured by creating instances internally. Moreover, internal methods have inherent advantages in accessing internal variables.
In fact, we can save the result of the instance inside the class, so that next time the existence of this value is detected, it can be taken out and used directly without re-creating it.
Of course, I have seen some books that make an empty __clone(){} method to prevent cloning, which is good. I leave the icing on the cake to specific projects.
Finally, let’s see how to use this singleton:
$db = DB::initDB(); //$db->somMethod();
Isn’t it very simple?
In addition, as for which methods should be static and which methods should not be used, my idea is that if the $this variable is accessed inside the method, then the static method should not be used, and vice versa. In other words, static methods can be used without instantiating objects.
Next time we will learn the factory model together
The above introduces the learning design pattern, including the content of design pattern (1). I hope it will be helpful to friends who are interested in PHP tutorials.