php aop实现
PHP 实现 AOP(面向切面编程)
AOP(Aspect-Oriented Programming)是一种编程范式,用于将横切关注点(如日志、事务、权限等)从业务逻辑中分离出来。PHP 可以通过以下几种方式实现 AOP:
使用 Go! AOP 框架
Go! AOP 是一个纯 PHP 实现的 AOP 框架,无需安装扩展。
安装:
composer require goaop/framework
示例代码:
use Go\Core\AspectKernel;
use Go\Core\AspectContainer;
class LoggingAspect implements \Go\Aop\Aspect
{
public function beforeMethod(\Go\Aop\Intercept\MethodInvocation $invocation)
{
echo "Calling method: " . $invocation->getMethod()->name;
}
}
class ApplicationAspectKernel extends AspectKernel
{
protected function configureAop(AspectContainer $container)
{
$container->registerAspect(new LoggingAspect());
}
}
ApplicationAspectKernel::getInstance()->init([
'debug' => true,
'appDir' => __DIR__,
'cacheDir' => __DIR__ . '/cache'
]);
使用 PHP-DI 和 AOP 集成
PHP-DI 是一个依赖注入容器,支持 AOP。

安装:
composer require php-di/php-di
composer require php-di/aop-bridge
示例代码:
use DI\ContainerBuilder;
use DI\Aop\Aspect;
class LoggingAspect
{
public function before()
{
echo "Before method execution";
}
}
$builder = new ContainerBuilder();
$builder->useAutowiring(true);
$builder->useAnnotations(true);
$builder->enableAop();
$container = $builder->build();
使用手动代理模式
如果没有框架支持,可以通过手动代理模式实现 AOP。

示例代码:
interface ServiceInterface
{
public function doSomething();
}
class RealService implements ServiceInterface
{
public function doSomething()
{
echo "Real service action";
}
}
class ProxyService implements ServiceInterface
{
private $realService;
public function __construct(ServiceInterface $realService)
{
$this->realService = $realService;
}
public function doSomething()
{
echo "Before action";
$this->realService->doSomething();
echo "After action";
}
}
$realService = new RealService();
$proxy = new ProxyService($realService);
$proxy->doSomething();
使用 runkit 扩展(已废弃)
runkit 是一个 PHP 扩展,可以动态修改类和函数,但已不再维护。
安装(不推荐):
extension=runkit.so
示例代码:
function log_wrapper($name, $args)
{
echo "Calling $name with " . json_encode($args);
return call_user_func_array($name, $args);
}
runkit_function_copy('target_function', 'target_function_original');
runkit_function_redefine('target_function', '', 'return log_wrapper("target_function_original", func_get_args());');
使用 AOP 的常见场景
- 日志记录:在方法调用前后记录日志。
- 事务管理:自动开启和提交事务。
- 权限检查:在方法执行前验证权限。
- 性能监控:统计方法执行时间。
注意事项
- Go! AOP 和 PHP-DI 需要 PHP 5.6 或更高版本。
- 代理模式会增加一定的性能开销。
- 动态修改代码(如 runkit)可能带来维护困难。
通过以上方法,可以在 PHP 中灵活实现 AOP,根据项目需求选择合适的方案。






