<?php
/**
* facade模式
* 将杂乱的代码封装为干净的接口
*
* 来自<<深入PHP面向对象,模式与实践>>
*/
/**
*
* 我们来看一下不使用facade模式比较极端的一个例子
* 以下代码只是为了从log中获取信息,并将其转为对象数据
*/
function getProductFileLines($file) {
return file($file);
}
function getProductObjectFromId($id, $productName) {
return new Product($id, $productName);
}
function getNameFromLine($line) {
if (preg_match("/.*-(.*)sd+/", $line, $arr)) {
return str_replace('_', ' ', $array[1]);
}
return '';
}
function getIdFromLine($line) {
if (preg_match("/^(d{1,3})-/", $line, $arr)) {
return $arr[1];
}
return -1;
}
class Product {
public $id;
public $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
}
/**
* 为杂乱的代码生成干净的接口
* 使用facade模式将上面的代码封装为干净的接口
*/
class ProductFacade {
private $products = array();
public function __construct($file) {
$this->file = $file;
$this->compile();
}
private function compile() {
$lines = getProductFileLines($this->file);
foreach($lines as $line) {
$id = getIdFromLine($line);
$name = getNameFromLine($line);
$this->products[$id] = getProductObjectFromId($id, $name);
}
}
public function getProducts() {
return $this->products;
}
public function getProduct($id) {
return $this->products[$id];
}
}
$facade = new ProductFacade('test.txt');
$product = $facade->getProduct(1234);