search
HomeBackend DevelopmentPHP TutorialPHP三层结构(下) PHP实现AOP_PHP

本文源码下载地址:http://xiazai.bitsCN.com/201007/yuanma/TraceLWord.rar
开发环境为 eclipse(pdt)
让我们把注意力集中到中间服务层上来。中间服务层代码比较简单,只是调用数据访问层代码将留言保存到数据库。如代码1所示:
复制代码 代码如下:
// 代码 1
// 中间服务层
class LWordServiceCore implements ILWordService {
// 添加留言
public function append($newLWord) {
// 调用数据访问层
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
}
};

在看到留言板的演示之后,公司的产品部和市场部或许会提出各种各样的想法和需求。比如他们希望在添加留言之前判断用户的权限!只有注册用户才能留言!我们需要修改代码,如代码2所示:
复制代码 代码如下:
// 代码 2, 增加登录验证
// 中间服务层
class LWordServiceCore implements ILWordService {
// 添加留言
public function append($newLWord) {
if (!($userLogin)) {
// 提示用户登录
}
// 调用数据访问层
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
}
};

市场部又希望在添加留言之前,对留言内容进行检查,如果留言中含有脏话就不保存。我们继续修改代码,如代码3所示:
复制代码 代码如下:
// 代码 3, 增加脏话过滤
// 中间服务层
class LWordServiceCore implements ILWordService {
// 添加留言
public function append($newLWord) {
if (!($userLogin)) {
// 提示用户登录
}
if (stristr($newLWord, "SB")) {
// 含有脏话, 提示留言发送失败
}
// 调用数据访问层
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
}
};

产品部也提出了新需求,他们希望加入积分机制。具体来讲就是在用户每次留言成功以后给用户+5分。我们继续修改代码,如代码4所示:
复制代码 代码如下:
// 代码 4, 加入留言积分机制
// 中间服务层
class LWordServiceCore implements ILWordService {
// 添加留言
public function append($newLWord) {
if (!($userLogin)) {
// 提示用户登录
}
if (stristr($newLWord, "SB")) {
// 含有脏话, 提示留言发送失败
}
// 调用数据访问层
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
// 给用户加分
$score = getUserScore($userName);
$score = $score + 5;
saveUserScore($userName, $score);
}
};

没过多久,产品部又对需求进行细化,他们希望用户积分每积累够1000分以后,就给用户升级。我们继续修改代码,如代码5所示:
复制代码 代码如下:
// 代码 5, 加入用户升级规则
// 中间服务层
class LWordServiceCore implements ILWordService {
// 添加留言
public function append($newLWord) {
if (!($userLogin)) {
// 提示用户登录
}
if (stristr($newLWord, "fuck")) {
// 含有脏话, 提示留言发送失败
}

// 调用数据访问层
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
// 给用户加分
$score = getUserScore($userName);
$score = $score + 5;
saveUserScore($userName, $score);
// 给用户升级
if (($score % 1000) == 0) {
$level = getUserLevel($userName);
$level = $level + 1;
saveUserLevel($userName, $level);
}
}
};

随着需求的增多,我们需要不断的修改中间服务层代码。但是你应该不难发现,需求越多中间服务层代码也就越多越庞大!最后会导致即便我们使用三层结构的开发模式,也还是没有有效的降低工程难度!另外就是应需求的变化而修改中间服务代码以后,需要重新测试所有代码,而不是有效的测试新增代码……

其实让我们仔细分析一下这个留言板代码,我先要提出一个主业务逻辑和次业务逻辑的概念。无论怎样,把留言内容存入到数据库,这是业务逻辑的主干!这个就是主业务逻辑!这部分没有随着需求的增加而修改。至于在存入数据库之前要进行权限校验,要进行内容检查,存入数据库之后要给用户加分,然后给用户升级,这些都是前序工作和扫尾工作,都是次业务逻辑!主业务逻辑几乎是一成不变的,次业务逻辑变化却非常频繁。为了提高代码的可读性和可维护性,我们可以考虑把这些次业务逻辑放到别的地方,尽量不要让它们干扰主业务逻辑。主业务逻辑专心干自己该干的事情好了,至于别的任何事情,主业务逻辑一概都不闻不问!那么我们的代码就可以写成这样,如代码6所示:
复制代码 代码如下:
// 代码 6, 将主业务逻辑和次业务逻辑分开
// 中间服务层
class LWordServiceCore implements ILWordService {
// 添加留言
public function append($newLWord) {
// 添加留言前
beforeAppend($newLWord);
// 调用数据访问层
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
// 添加留言后
behindAppend($newLWord);
}
};

我们可以把权限判断代码和留言内容文本过滤代码统统塞进beforeAppend函数,把用户积分代码塞进behindAppend函数,这样就把次业务逻辑从主业务逻辑代码中清理掉了。主业务逻辑知道有个“序曲”函数beforeAppend,有个“尾声”函数behindAppend,但是在序曲和尾声函数中具体都做了什么事情,主业务逻辑并不知道,也不需要知道!当然实际编码工作并不那么简单,我们还要兼顾产品部和市场部更多的需求变化,所以最好能实现一种插件方式来应对这种变化,但是仅仅依靠两个函数beforeAppend和behindAppend是达不到这个目的~

想要实现插件方式,可以建立接口!使用接口的好处是可以将定义和实现隔离,另外就是实现多态。我们建立一个留言扩展接口ILWordExtension,该接口有两个函数beforeAppend和behindAppend。权限校验、内容检查、加分这些功能可以看作是实现ILWordExtension接口的三个实现类,主业务逻辑就依次遍历这三个实现类,来完成次业务逻辑。如图1所示:
CheckPowerExtension扩展类用作用户权限校验,CheckContentExtension扩展类用作留言内容检查,AddScoreExtension扩展类用作给用户加分和升级。示意代码如代码7所示:
PHP三层结构(下) PHP实现AOP_PHP
(图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函数里即可。程序从此有了条理,并且算是具备了可扩展性。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use