"Seven-day self-made PHP framework" third Day: PHP implementation design pattern

Source: Internet
Author: User
Tags php framework sprintf

Previous review: "seven-day PHP framework" the next day: Model and database, click here

Original address: http://www.cnblogs.com/sweng/p/6624845.html, welcome attention: Programming Old man

Why use Design patterns?

Design patterns, my understanding is to achieve the "reusable" goal, and design a set of mutually collaborative classes.

Interested readers can read the design patterns:elements of reusable object-oriented software, with four authors (Gang of four) listing 23 of the industry's best-known patterns.

Here we first introduce the three design patterns that our framework will cover.

Singleton mode (singleton)

Singleton mode can guarantee that a class has only one object instance, which is commonly used in database access classes, thus saving the consumption of hardware resources.

Here, we rewrite the previous section of the MySQL class

Class MySQL extends db{private static $instance =null;public static function getinstance () {if (self:: $instance ==null) { Self:: $instance =new MySQL ();} Return self:: $instance;} Public Function MySQL () {/*config*/$this->ip= ' * '; $this->serverid= ' * '; $this->serverpassword= ' * '; $this- >databasename= ' * ';/*end of config*/$this->connection=mysqli_connect ($this->ip, $this->serverid, $this- >serverpassword, $this->databasename), if (! $this->connection) {die (' Could not connect '. $this connection);} Mysqli_query ($this->connection, ' Set names UTF8 ');} Public Function Execute ($sql) {return mysqli_query ($this->connection, $sql);} Public Function Query ($sql) {$result =mysqli_query ($this->connection, $sql); $arr =array (); and while ($row =mysqli_fetch _array ($result)) {$arr []= $row;} return $arr;} Public Function Close () {mysqli_close ($this->connection);}}

It is important to note that if you instantiate a MySQL class, we no longer write

$db =new MySQL ();

But this:

$db =mysql::getinstance ();

Because only getinstance is a static function, the constructor of the MySQL class is guaranteed to be called only once.

Singleton mode is a very common design pattern, which is not mentioned here.

Appearance mode (facade)

Because of the namespace problem, the appearance pattern can guarantee that many methods of a class seem to be "provided by a class", where we first design a simple service provider class

Class Serviceprovider{public function Write ($arg) {echo $arg;}}

This class has only one write method, which is to print out the parameters

Then define a facade class

Class Facade{public static function getinstance ($classname, $args) {return new $classname ($args);} public static function Getfacadeaccessor () {//}public static function __callstatic ($method, $args) {$instance =static:: GetInstance (Static::getfacadeaccessor (), $args), Return Call_user_func_array (Array ($instance, $method), $args);}}

To understand this class, we just focus on the last function, the __callstatic magic method. This method is called the __callstatic method when the facade type object or its subclass calls a function that he does not define, and the method finally calls the Call_user_func_array function. is to give the task to the class that provides the service to complete, and to complete the transfer of parameters.

Let's write another facade subclass.

Class Myfacade extends facade{public static function Getfacadeaccessor () {return serviceprovider::class;}}

Notice here that the subclass implements the Getfacadeaccessor method that the parent class does not implement specifically, and this method is to tell the __callstatic method of the parent class: "What kind of class do I represent as a facade, the task is to be realized by him", from the grammatical point of view, Just returns a String representing the class name. So the parent does not know at first that its subclasses represent what "service provider class", only if the subclass's static function is called, because the subclass does not have the static function, so the __callstatic method of the parent class is started.

Abstract Factory (Factory)

I have a vulgar understanding of the abstract factory: "Object and string Correspondence", that is, a string can be used to create a class object. This approach is mostly useful in two situations:

1. Class name is not stable, will be frequently modified in the project

The class name modification, many times is not the designer "the name neat" or "the name Obsessive-Compulsive disorder" causes the modification, but in the project unceasing iteration, discovered this kind of design unreasonable. If this class is not used frequently, then change the class name as long as the manual to make some small changes, but if this class throughout the code (if it is a database class), the modification work is large, of course, we can also use the code file "string substitution", but if a PHP written project, PHP files are dozens of hundred, which is also unreasonable.

2. The designer of the class is not the user of the class

The designer of the class and the user of the class are not the same developers, so remembering a string may be more vivid than remembering a class name. We have all learned the principle of computer networks, all know that the memory of a domain name than the memory of an IP address to be more vivid, this is the problem of DNS resolution.

Because the abstract factory a lot of teaching materials are involved, no longer repeat, this article will introduce a very popular service container at present.

We hope that the whole project, DB class, Session class, FileSystem class, "Take to use", without each tedious initialization, such as write $db=new db (ARG1,ARG2), such statements, also want the DB and other types of objects like a "global" variable general, It can be called at any time during the entire program run.

The service container allows programmers of all types to call the DB without having to know the details of the class, or even create an object with an alias for the string.

We define a service container class

Class Container{public $bindings;p ublic function bind ($abstract, $concrete) {$this->bindings[$abstract]= $concrete ;} Public function make ($abstract, $parameters =[]) {return Call_user_func_array ($this->bindings[$abstract],$ parameters);}}

The service container can be viewed simply as a global variable, and the Bind method is to bind strings and constructors with associative arrays.

Now, with the service container, our model class is going to be modified.

Class Model implements Imodel{public static $table;p ublic static $container;p ublic static $db;p ublic function __construct () {self:: $container =new container (); Self:: $container->bind (' db ', function () {return mysql::getinstance ();}); Self:: $db =self:: $container->make (' db ', []);} public static function Get ($id) {return self::where (' id ', $id);} public static function where ($condition, $value) {$sql =sprintf ("select * from%s where%s= '%s '", Self:: $table, $condition, $value); return self:: $db->query ($sql);} public static function All () {$sql =sprintf (' select * from%s ', Self:: $table); return self:: $db->query ($sql)}}

Observing the code above, we used both a singleton pattern and a service container.

Summary: If you want to make a PHP framework, you should do a good job of reusing code. Design patterns have been the focus of many debates, "should we use design patterns?" "At the beginning of this article, I also try to avoid" too tangled up in this problem ", I think, the design pattern has its existence value, at least in the specific project, indeed in many version iterations save the workload, improve efficiency, but if in a small project in order to" show I will design patterns "and use design patterns, it is unreasonable.

"Seven-day self-made PHP framework" third Day: PHP implementation design pattern

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.