microAOP 是一个PHP编写的简洁而强大的AOP库,除去空行和注释,有效代码不到300行,却实现了很多有用的特性,让PHP也能简单的实现AOP编程。如果你想在已有的项目中使用AOP编程,通过microAOP将会变得非常轻松,你只需要增加你所有需要的切面类,在原有代码改动最少的情况下就可以轻松实现AOP。
microAOP 可以通过 composer 安装,安装步骤非常简单:
使用以下命令从 composer 下载 microAOP:
$ composer require dongnan/microaop
Composer 会将 microAOP 安装到你的项目中,安装路径: vendor/dongnan/microaop
<?php namespace yournamespace; class Model { public function save() { echo __METHOD__ . ' has been executed' . PHP_EOL; } }
<?php namespace yournamespace; class Aspect { public function saveBefore($params) { echo '------------------------------------------' . PHP_EOL; echo __METHOD__ . ' has been executed' . PHP_EOL; } public function saveAfter($params) { echo '------------------------------------------' . PHP_EOL; echo __METHOD__ . ' has been executed' . PHP_EOL; } }
<?php use microAOP/Proxy; use yournamespace/Model; use yournamespace/Aspect; $model = new Model(); //Just bind it Proxy::__bind__($model, new Aspect()); $model->save();
执行后输出:
------------------------------------------ Aspect::saveBefore has been executed Model::save has been executed ------------------------------------------ Aspect::saveAfter has been executed
请参考项目中 examples 目录的内容