Design Mode of self-made PHP framework and php Framework Design Mode

Source: Internet
Author: User

Design Mode of self-made PHP framework and php Framework Design Mode

Why is the design pattern used?

I understand the design pattern as a set of collaborative classes designed to achieve the "Reusable" goal.

Interested readers can read Design Patterns: Elements of Reusable Object-Oriented Software. The Four authors (Gang of Four) List 23 well-known Design Patterns in the book.

Here we will first introduce the three design modes involved in our framework.

Singleton)

The Singleton mode ensures that a class has only one object instance and is often used in database access classes to save the consumption of hardware resources.

Here, we will rewrite the MySQL class in the previous chapter.

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();while($row=mysqli_fetch_array($result)){$arr[]=$row;}return $arr;}public function Close(){mysqli_close($this->connection);}}

Note that if you instantiate a MySQL class

$db=new MySQL();

But like this:

$db=MySQL::getInstance();

Only the getInstance static function can ensure that only the MySQL class constructor is called once.

The Singleton mode is a common design mode, which is not described here.

Facade)

Because of namespace problems, the appearance mode can ensure that many methods of a class seem to be provided by a class. Here 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 only need to pay attention to the last function, which is the _ callstatic magic method. This method is used to call the _ callstatic method when a Facade-type object or its subclass calls a function that is not defined by itself. This method finally calls the call_user_func_array function, that is, the task is handed over to the class that provides this service for completion, and parameter transmission is completed at the same time.

Let's write another Facade subclass.

class MyFacade extends Facade{public static function getFacadeAccessor(){return ServiceProvider::class;}}

Note that the subclass implements the getFacadeAccessor method that is not specifically implemented by the parent class. This method is to tell the _ callstatic method of the parent class: "I act as a Facade, which class represents, the task is implemented by him. "In terms of syntax, only a string representing the class name is returned. Therefore, at first, the parent class does not know what its subclass represents. Only when the static function of the subclass is called, because the subclass does not have this static function, therefore, the _ callstatic method of the parent class is started.

Abstract Factory)

I have a vulgar understanding of the abstract factory: "The correspondence between objects and strings", that is, using a string can create a class object. This method is convenient in two cases:

1. The class name is unstable and will be modified frequently in the project.

The modification of the class name is often not caused by the designer's "Naming cleanliness" or "Naming obsessive-compulsive disorder", but by the continuous iteration of the project, it is found that the class design is unreasonable. If this class is not frequently used, you only need to manually modify the class name. However, if this class exists in the Code (for example, the database class ), the modification workload is huge. Of course, we can also use "string replacement" for code files. However, if a PHP project contains dozens or hundreds of PHP files, this is also unreasonable.

2. The class designer is not a class user.

If the class designer and the class user are not the same developer, the memory of a string may be much more vivid than the memory of a class name. We have learned the principles of computer networks and know that remembering a domain name is much more vivid than remembering an IP address. This is the DNS solution.

Because many textbooks in the abstract factory are involved, we will not repeat them here. This article will introduce the very popular service containers.

We hope that the DB, Session, and FileSystem classes in the entire project will be "ready for use" without every tedious initialization, such as writing $ db = new DB (arg1, arg2 ); such statements also require DB and other types of objects to be like a "global" variable and can be called at any time during the entire program running.

The service container allows programmers who call DB and other types to avoid having to know too much details about this class, or even use a string alias to create such an object.

We define a service container class

class Container{public $bindings;public 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 simply regarded as a global variable. The bind method is to bind the string and the constructor with an associated array.

Now, with the service container, our Model class is about to be modified.

class Model implements IModel{public static $table;public static $container;public static $db;public 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);}}

Observe the code above. We also use the singleton mode and service container.

Conclusion: If you want to build a PHP framework, you should reuse the code. Design patterns have always been the focus of a lot of debate. "Should we use design patterns ?", At the beginning of this article, I also tried to avoid "Too tangle with this problem". I believe that the design model has its own value, at least in a specific project, it does save effort and improve work efficiency in many version iterations, but it is unreasonable to use the design pattern in a small project to "show off my design patterns.

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.