6.2 PHP实践
目前的PHP来说,还没有一个完整的AOP内置实现,虽然出现了RunKit, 但一直都以BETA的状态呆在PECL项目里,估计很长时间内不太可能成为PHP的缺省设置。那是不是AOP在PHP里就破灭了呢?当然不是,因为我们有 __get(),__set(),__call()等魔术方法,合理使用这些方法可以为我们实现某种程度的“准AOP”能力,之所以说是准AOP,是因为 单单从实现上来看,称其为AOP有些牵强,但是从效果上来看,又部分实现了AOP的作用,虽然其实现方式并不完美,但对于一般的使用已经足够了。
<?php
/**
* 应用程序中某个业务逻辑类
*
*/
class Target
{
public function foobar(){
echo '业务逻辑<br />';
}
}
//业务逻辑类的包装类
class AOP
{
private $instance;
public function __construct($instance) {
$this->instance = $instance;
}
public function __call($method, $param) {
if(! method_exists($this->instance, $method)) {
throw new Exception("Call undefinded method ".get_class($this->instance)."::$method");
}
//前增强
$this->before();
$callBack = array($this->instance, $method);
$return = call_user_func_array($callBack, $param);
$this->after();
return $return;
}
/**
* 前增强
*
*/
public function before() {
echo '权限检查<br />';
}
/**
* 后增强
*
*/
public function after() {
echo '日志记录<br />';
}
}
/**
* 工厂方法
*
*/
class Factory
{
public function getTargetInstance(){
return new AOP(new Target());
}
}
//客户端调用演示
header("Content-Type: text/html; charset=utf8");
try {
$obj = Factory::getTargetInstance();
$obj->foobar();
} catch(Exception $e) {
echo 'Caught exception: ', $e->getMessage();
}
利用php5内置的魔术方法__call来实现AOP,唯一的缺点是要在AOP类里面实例客户端对象,返回的是被AOP包装后的对象。因此像get_class会遇到麻烦。
比 如说,客户端通过getBizInstance()方法以为得到的对象是Target,但实际上它得到的是一个Target的包装对象AOP,这样的话, 如果客户端进行一些诸如get_class()之类和对象类型相关的操作就会出错,当然,大多数情况下,客户端似乎不太会做类似的操作。
我们用 runkit 扩展来实现方法调用拦截的例子:
也有人用了继承方式来实现:
/**
* 应用程序中某个业务逻辑类
*
*/
class Target
{
public function foobar(){
echo '业务逻辑<br />';
}
}
runkit_method_rename('Target', 'foobar', '#foobar');
runkit_method_add('Target','add','$a,$b','
echo "before call\n";
$ret = $this->{"#foobar"}($a,$b);
echo "after call\n";
return $ret;
');
这个有明显的缺点:
<?php
//业务逻辑类的包装类
class AOP
{
private $instance;
public function __construct() {
}
public function __call($method, $param) {
if(strchr($method,'Aop_')){
$method = str_replace('Aop_','',$method);
if(! method_exists($this, $method)) {
throw new Exception("Call undefinded method ".get_class($this)."::$method");
}
}
//前增强
$this->before();
$callBack = array($this, $method);
$return = call_user_func_array($callBack, $param);
$this->after();
return $return;
}
/**
* 前增强
*
*/
public function before() {
echo '权限检查<br />';
}
/**
* 后增强
*
*/
public function after() {
echo '日志记录<br />';
}
}
/**
* 应用程序中某个业务逻辑类
*
*/
class Target extends AOP
{
public function foobar(){
echo '业务逻辑<br />';
}
}
//客户端调用演示
header("Content-Type: text/html; charset=utf8");
try {
$obj = new Target();
$obj->Aop_foobar();
} catch(Exception $e) {
echo 'Caught exception: ', $e->getMessage();
}
1)严格的限制,如需要增强的方法名需要加AOP前缀。
2)如果Target类已经继承另外的父类,无法在继承AOP类。
3) AOP的实现,一个很重要的前提就是不能对源代码有很明显的侵入,而这里增强的目标对象要继承AOP类,无疑侵入了对象.
除了以上的实现方法,我们可以使用配置文件来配置把哪些关注点代码增强到目标对象的切入点上。
转载于:https://blog.51cto.com/haocaige/1440864