PHP三层结构(下) PHP实现AOP第1/2页

2019-04-09 17:40:20于海丽

CheckPowerExtension扩展类用作用户权限校验,CheckContentExtension扩展类用作留言内容检查,AddScoreExtension扩展类用作给用户加分和升级。示意代码如代码7所示:

(图1),加入扩展接口

// 代码 7,加入扩展接口
// 扩展接口
interface ILWordExtension {
// 添加留言前
public function beforeAppend($newLWord);
// 添加留言后
public function behindAppend($newLWord);
};

// 检查权限
class CheckPowerExtension implements ILWordExtension {
// 添加留言前
public function beforeAppend($newLWord) {
// 在这里判断用户权限
}

// 添加留言后
public function behindAppend($newLWord) {
}
};

// 检查留言文本
class CheckContentExtension implements ILWordExtension {
// 添加留言前
public function beforeAppend($newLWord) {
if (stristr($newLWord, "SB")) {
throw new Exception();
}
}

// 添加留言后
public function behindAppend($newLWord) {
}
};

// 用户积分
class AddScoreExtension implements ILWordExtension {
// 添加留言前
public function beforeAppend($newLWord) {
}

// 添加留言后
public function behindAppend($newLWord) {
// 在这里给用户积分
}
};

// 中间服务层
class LWordServiceCore implements ILWordService {
// 添加留言
public function append($newLWord) {
// 添加留言前
$this->beforeAppend($newLWord);

// 调用数据访问层
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);

// 添加留言后
$this->behindAppend($newLWord);
}

// 添加留言前
private function beforeAppend($newLWord) {
// 获取扩展数组
$extArray = $this->getExtArray();

foreach ($extArray as $ext) {
// 遍历每一个扩展, 并调用其 beforeAppend 函数
$ext->beforeAppend($newLWord);
}
}

// 添加留言后
private function behindAppend($newLWord) {
// 获取扩展数组
$extArray = $this->getExtArray();

foreach ($extArray as $ext) {
// 遍历每一个扩展, 并调用其 behindAppend 函数
$ext->behindAppend($newLWord);
}
}

// 获取扩展数组,
// 该函数的返回值实际上是 ILWordExtension 接口数组
private function getExtArray() {
return array(
// 检查权限
new CheckPowerExtension(),
// 检查内容
new CheckContentExtension(),
// 加分
new AddScoreExtension(),
);
}
};

如果还有新需求,,我们只要再添加ILWordExtension 实现类并且把它注册到getExtArray函数里即可。程序从此有了条理,并且算是具备了可扩展性。

12下一页阅读全文
相关文章 大家在看