Learn design patterns

WBOY
Release: 2016-08-08 09:33:09
Original
901 people have browsed it


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:

<span>//</span><span>get data class</span> <span>class</span><span> DB { </span><span>private</span> <span>$_db</span><span>; </span><span>private</span> <span>static</span> <span>$_instance</span><span>; </span><span>private</span> <span>function</span><span> __construct(){ </span><span>$DSN</span> = '../../content/xxtebook.db'<span>; </span><span>$this</span>->_db = <span>new</span> PDO('sqlite:'.<span>$DSN</span><span>);
    } </span><span>//</span><span>初始化数据库连接</span> <span>public</span> <span>static</span> <span>function</span><span> initDB(){ </span><span>if</span>(! (self::<span>$_instance</span><span> instanceof self)){
            self</span>::<span>$_instance</span> = <span>new</span><span> self();
        } </span><span>return</span> self::<span>$_instance</span><span>;
      } </span><span>//</span><span>其它方法</span> <span> }</span>
Copy after login

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:

<span>$db</span> = DB::<span>initDB(); </span><span>//</span><span>$db->somMethod();</span>
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!