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 等等)。