在软件开发中,我们经常会遇到一些横切关注点(cross-cutting concerns),例如日志记录、事务管理、安全控制等。这些关注点会散布在多个模块中,导致代码冗余、难以维护。面向切面编程(AOP)是一种解决这类问题的有效方法,它可以将这些横切关注点从业务逻辑中分离出来,集中进行管理。
ray.aop 是一个 php 的 aop 框架,它允许我们在方法执行前后、抛出异常时等关键时刻插入自定义代码,实现对方法调用的拦截和增强。
问题:周末禁用方法调用
假设我们有一个披萨账单系统,为了保证送货员的休息,我们希望禁止在周末调用 chargeOrder 方法。
解决方案
- 定义注解
首先,我们定义一个 NotOnWeekends 注解,用于标记需要进行周末禁用的方法:
<?php use Attribute; #[Attribute(Attribute::TARGET_METHOD)] final class NotOnWeekends { }
- 标记方法
然后,我们在 RealBillingService 类的 chargeOrder 方法上添加 @NotOnWeekends 注解:
<?php class RealBillingService { #[NotOnWeekends] public function chargeOrder(PizzaOrder $order, CreditCard $creditCard) { // ... } }
- 实现拦截器
接下来,我们创建一个 WeekendBlocker 拦截器,实现 MethodInterceptor 接口。在 invoke 方法中,我们判断当前是否为周末,如果是,则抛出异常,否则继续执行原方法:
<?php use RayAopMethodInterceptor; use RayAopMethodInvocation; use RuntimeException; class WeekendBlocker implements MethodInterceptor { public function invoke(MethodInvocation $invocation) { $today = getdate(); if ($today['weekday'][0] === 'S') { throw new RuntimeException( $invocation->getMethod()->getName() . " not allowed on weekends!" ); } return $invocation->proceed(); } }
- 配置 Aspect
最后,我们使用 Aspect 类将注解、拦截器和目标类绑定在一起:
<?php use RayAopAspect; use RayAopMatcher; $aspect = new Aspect(); $aspect->bind( (new Matcher())->any(), (new Matcher())->annotatedWith(NotOnWeekends::class), [new WeekendBlocker()] ); $billing = $aspect->newInstance(RealBillingService::class); try { echo $billing->chargeOrder(); // Interceptors applied } catch (RuntimeException $e) { echo $e->getMessage() . "n"; exit(1); }
这段代码的含义是:
- (new Matcher())->any():匹配所有类。
- (new Matcher())->annotatedWith(NotOnWeekends::class):匹配带有 NotOnWeekends 注解的方法。
- [new WeekendBlocker()]:使用 WeekendBlocker 拦截器。
运行结果
如果在周末运行上述代码,将会抛出异常,提示 chargeOrder not allowed on weekends!。
Ray.Aop 的优势
- 代码解耦:将横切关注点从业务逻辑中分离出来,降低代码耦合度。
- 易于维护:集中管理横切关注点,方便修改和维护。
- 提高可读性:业务逻辑更加清晰,易于理解。
- 支持 PECL 扩展:安装 PECL 扩展后,可以实现更强大的 AOP 功能,例如拦截 final 类和方法。
实际应用效果
通过使用 Ray.Aop,我们可以轻松实现各种 AOP 需求,例如:
- 日志记录:记录方法调用信息,方便调试和分析。
- 事务管理:在方法执行前后开启和提交事务,保证数据一致性。
- 安全控制:验证用户权限,防止非法访问。
- 性能监控:统计方法执行时间,优化程序性能。
总之,Ray.Aop 是一个功能强大、易于使用的 AOP 框架,可以帮助我们更好地管理横切关注点,提高代码质量。 composer在线学习地址:学习地址