PHP最常用的设计模式
工厂模式
<?php
class Automobile
{
private $vehicleMake;
private $vehicleModel;
public function __construct($make, $model)
{
$this->vehicleMake = $make;
$this->vehicleModel = $model;
}
public function getMakeAndModel()
{
return $this->vehicleMake . ' ' . $this->vehicleModel;
}
}
class AutomobileFactory
{
public static function create($make, $model)
{
return new Automobile($make, $model);
}
}
// 用工厂的 create 方法创建 Automobile 对象
$veyron = AutomobileFactory::create('Bugatti', 'Veyron');
print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron"
上面的代码用来一个工厂来创建 Automobile 对象。用这种方式创建对象有两个好处: 首先,如果你后续需要更改,重命名或替换 Automobile 类,你只需要更改工厂类中的代码,而不是在每一个用到 Automobile 类的地方修改; 其次,如果创建对象的过程很复杂,你也只需要在工厂类中写,而不是在每个创建实例的地方重复地写。
当然,用工厂模式并不总是必要(或者明智)。上面的示例代码很简单,在实践中,工厂类中会被加入一些不必要的复杂性。 如果你是在做一个很大很复杂的项目,使用工厂模式将会给你省去很多麻烦。
策略模式
Interface,首先三个不同的类使用一个接口
<?php interface OutputInterface { public function load(); } class SerializedArrayOutput implements OutputInterface { public function load() { return serialize($arrayOfData); } } class JsonStringOutput implements OutputInterface { public function load() { return json_encode($arrayOfData); } } class ArrayOutput implements OutputInterface { public function load() { return $arrayOfData; } }
利用OutputInterface,提供了灵活性,上面三个类都可以作为参数
<?php class SomeClient { private $output; public function setOutput(OutputInterface $outputType) { $this->output = $outputType; } public function loadOutput() { return $this->output->load(); } }
这个属性被设置为具体的实例(三个输出类中之一的实例),并且 loadOutput 方法被调用,那么它的 load 方法就会被调用,返回回序列化结果或 json 或数组。
<?php $client = new SomeClient(); // Want an array? $client->setOutput(new ArrayOutput()); $data = $client->loadOutput(); // Want some JSON? $client->setOutput(new JsonStringOutput()); $data = $client->loadOutput();
前端控制器模式
前端控制器模式就是给你的 web 应用程序设置单一的入口(比如 index.php),用来集中处理所有请求的机制。 它的职责是载入所有依赖,处理请求,并发送响应给浏览器。前端控制器模式对整个架构是有益的,因为它鼓励模块化代码,并给了你一个单入口,可以写一些每个请求都需要跑的代码(比如输入数据的过滤)
模型-视图-控制器(MVC)
模型-视图-控制器 (MVC) 模式还有和它相关的 HMVC、HVVM 让你根据逻辑对象的不同作用去解耦。 模型用来作为数据访问层,并以应用中通用的格式返回数据。 控制器处理请求,处理从模型层返回的数据,并载入视图,发送响应。 视图用来展示需要在响应中使用的模板(markup, xml 等等)。