32.27. AOP(Aspect Oriented Programming)
<?php
interface Account{
public function hello($str);
}
class Demo implements Account{
public function __construct(){}
public function hello($str = ""){
echo 'Hello: '.$str;
}
public function __destruct(){}
}
class Aop
{
private $instance;
public function __construct($instance){
$this->instance = $instance;
}
public function __call($method, $argument){
if(! method_exists($this->instance, $method)){
throw new Exception('Undefine function: ' . $method);
}
/* 此處加入before代碼 */
$callBack = array($this->instance, $method);
$return = call_user_func_array($callBack, $argument);
/* 此處加入after代碼 */
return $return;
}
}
class Factory
{
public function __construct(){}
public function getInstance(){
return new Aop(new Demo());
}
}
try
{
$factory = Factory::getInstance();
$factory->hello('world');
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}