跳转到内容
文档

行为与匹配规则

编写 behavior 的完整参考:behavior 是框架在你的代码周围运行的动态 middleware,matching rule 则说明它们作用于哪里。

本页译自英文,以英文页面为准。 阅读原文

本页涵盖使用框架时你要编写的一切:behavior class(行为类)、其中作为动态 middleware(中间件)在你的代码周围运行的 behavior(行为)、每个 behavior 收到的 call context(调用上下文),以及选择它在哪里运行的 matching rule(匹配规则)。如果你还没有配置内核,请从 快速上手 开始。从问题到可运行代码的完整演练,见 缓存行为 和 日志行为。

框架的 API 保留了经典的命名,所以你会在代码、类名和错误信息中遇到它们。本文档使用日常用语,并只在一处给出对应的 API 术语:

本文档用语 API 中的名称 含义
Behavior class(行为类) Aspect(切面) 实现了 Go\Aop\Aspect 的类,把相关的 behavior 组织在一起
Behavior(行为),即 middleware(中间件) Advice(通知) Behavior class 中的一个 public 方法,带有一个来自 Go\Lang\Attribute 的注解:#[Before]、#[After]、#[AfterThrowing] 或 #[Around]
Matching rule(匹配规则) Pointcut(切入点) 该注解中的表达式,选择 behavior 在哪里运行
Call context(调用上下文) Joinpoint(连接点) 被拦截的那一刻(一次方法调用、一次属性访问、一次对象创建),以对象的形式传给 behavior
Compile step(编译步骤) Weaving(织入) 把你的类转换成 PHP 加载的文件,并挂接上 behavior
Class extension(类扩展) Introduction(引入) 添加到现有类上的一个接口和一个 trait
src/Aspect/ServiceAspect.php
namespace App\Aspect;
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\AfterThrowing;
use Go\Lang\Attribute\Around;
use Psr\Log\LoggerInterface;
class ServiceAspect implements Aspect
{
public function __construct(private readonly LoggerInterface $logger) {}
#[Around('execution(public App\Service\*->*(*))')]
public function measure(MethodInvocation $invocation): mixed
{
$start = hrtime(true);
try {
return $invocation->proceed();
} finally {
$this->logger->debug($invocation . ' took ' . (hrtime(true) - $start) . ' ns');
}
}
#[AfterThrowing('execution(public App\Service\*->*(*))')]
public function logFailure(MethodInvocation $invocation, \Throwable $exception): void
{
$this->logger->error($invocation . ' failed: ' . $exception->getMessage());
}
}

Behavior class 是一个实现了 Go\Aop\Aspect 的普通 PHP 类。它承载日志、缓存、安全检查或事务这类原本会被复制到许多类中的逻辑。它的每个 behavior 都作为 middleware 在其 matching rule 选中的代码周围运行:上面的 measure() 包裹 App\Service 中的每个 public 方法,而 logFailure() 在其中某个方法抛出异常时运行。因为它是一个普通的类,你可以使用构造函数注入、私有状态、trait 以及 PHP 提供的其他一切。

Behavior 上的注解说明它相对于被拦截的调用何时运行。

注解 运行时机
#[Before] 在调用之前。它可以用 setArguments() 修改参数。
#[After] 在调用之后,调用抛出异常时也会运行(类似 finally)。
#[AfterThrowing] 在调用抛出异常时。它把异常作为第二个参数接收;之后异常会被重新抛出。
#[Around] 代替调用运行,就像 middleware 那样。它决定是否调用 proceed(),它的返回值就是调用的结果。

这四个注解都位于 Go\Lang\Attribute 命名空间中,并以一条 matching rule 作为参数。

src/Aspect/MonitorAspect.php
namespace Aspect;
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Before;
class MonitorAspect implements Aspect
{
#[Before('execution(public Example->*(*))')]
public function beforeMethodExecution(MethodInvocation $invocation): void
{
echo 'Calling Before Interceptor for: ',
$invocation,
' with arguments: ',
json_encode($invocation->getArguments()),
"<br>\n";
}
}

Before behavior 在原始方法之前运行。用它来校验输入或检查权限。要改变原始方法接收到的内容,替换参数即可:

#[Before('execution(public App\Service\UserService->rename(*))')]
public function trimName(MethodInvocation $invocation): void
{
$arguments = $invocation->getArguments();
$arguments[0] = trim($arguments[0]);
$invocation->setArguments($arguments);
}

getArguments() 按位置列出参数,所以要用索引访问它们。

use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\After;
#[After('execution(public App\Service\ImportService->run(*))')]
public function releaseLock(MethodInvocation $invocation): void
{
$this->lock->release();
}

After behavior 的作用类似 finally 块:无论方法正常返回还是抛出异常,它都会运行。用它来释放资源或停止计时器。

use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\AfterThrowing;
#[AfterThrowing('execution(public App\Service\*->*(*))')]
public function logFailure(MethodInvocation $invocation, \Throwable $exception): void
{
$this->logger->error($invocation . ' failed: ' . $exception->getMessage());
}

AfterThrowing behavior 只在调用抛出异常时运行。它把异常作为第二个参数接收。框架会在 behavior 之后重新抛出异常,所以调用方仍然能看到它。用它来记录错误或发送告警。

use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Around;
#[Around('execution(public App\Service\*->*(*))')]
public function measure(MethodInvocation $invocation): mixed
{
$start = hrtime(true);
try {
return $invocation->proceed();
} finally {
$this->logger->debug($invocation . ' took ' . (hrtime(true) - $start) . ' ns');
}
}

Around behavior 代替调用运行,就像 HTTP 栈中的 middleware。你调用 proceed() 把控制权交给原始代码,而 behavior 返回的任何值都会成为调用结果。这使 Around 成为能力最强的类型:它决定原始代码是否运行,可以在 proceed() 之前修改参数,可以修改返回值,还可以捕获异常。用它来实现缓存、事务和重试逻辑。

如果你不调用 proceed(),原始方法就不会运行:

#[Around('execution(public App\Service\ReportService->build(*))')]
public function cacheReport(MethodInvocation $invocation): mixed
{
$key = $invocation . json_encode($invocation->getArguments());
return $this->reports[$key] ??= $invocation->proceed();
}

每个 behavior 都会收到一个描述被拦截调用的对象:调用的参数、它所运行的对象,以及用来继续执行的 proceed()。它的类取决于 matching rule 选中的是什么。

类 何时收到 主要方法
MethodInvocation 动态方法和静态方法的 execution() getThis()、getScope()、getMethod()、getArguments()、setArguments()、proceed()
FunctionInvocation 带命名空间的函数的 execution() getFunction()、getArguments()、setArguments()、proceed()
FieldAccess 属性的 access() getThis()、getField()、getAccessType()、getValue()、getValueToSet()、proceed()
ConstructorInvocation initialization() getConstructor()、getArguments()、getThis()(对象创建之前为 null)、proceed()

它们都位于 Go\Aop\Intercept 中。MethodInvocation 可以当作字符串使用,上面的示例在日志消息中就是这么做的。

这些类声明了 @template 类型,因此 PHPStan 和 IDE 知道 getThis() 和 proceed() 的类型。在你的 behavior 的 docblock 中写出具体类型:

use App\Model\Order;
use App\Service\OrderService;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Around;
/**
* @param MethodInvocation<OrderService, Order> $invocation
*/
#[Around('execution(public App\Service\OrderService->place(*))')]
public function auditOrder(MethodInvocation $invocation): Order
{
$order = $invocation->proceed();
// …
return $order;
}

这里的 MethodInvocation<OrderService, Order> 告诉分析器:getThis() 是一个 OrderService,proceed() 返回一个 Order。

挂接 behavior 的背后没有任何魔法。对每个被拦截的方法,框架都会生成一条普通的 middleware 链。每个 behavior 都以一个用 一等可调用语法 创建的闭包来引用,直接取自 behavior class 实例:

static $__joinPoint = InterceptorInjector::forMethod(
self::class,
'doSomething',
[
Interceptor::before(The::aspect(MonitorAspect::class)->beforeMethodExecution(...)),
],
$this->doSomethingOriginalAlias(...),
);

The::aspect() 从内核容器中取出 behavior class 实例,->beforeMethodExecution(...) 就是你编写的 behavior 方法。你可以在 IDE 里按住 Ctrl 点击跳转到它,在其中设置断点,并像调试手写代码一样单步调试生成的代码。Call context 在编译期构建并缓存在生成的代码中,因此运行时没有反射,也不解析注解。关于生成的代码,详见 Debuggable。

以普通闭包(而不是 behavior class 的方法)注册到容器中的 behavior,则通过惰性的 The::advice() 访问器挂接。它按标识符查找已注册的条目,并把它解包为原始闭包:

Interceptor::around(The::advice('advisor.Demo\Aspect\DynamicMethodsAspect->aroundMagicMethods')),

Matching rule 是一个表达式,用来选择 behavior 在哪里运行:方法执行、属性访问、函数调用或对象创建。它是 behavior 注解的参数:

#[Before('execution(public App\Service->save(*))')]

在 playground 中,你可以针对一个 PHP 文件试验规则;本节是完整的参考。

规则 选中
execution(modifiers Class->method(*)) 动态方法的执行
execution(modifiers Class::method(*)) 静态方法的执行
execution(Namespace\function(*)) 在该命名空间中对系统函数的调用
access(modifiers Class->property) 对实例属性的读和写
within(ClassFilter) 匹配类的所有成员(方法和属性)
initialization(ClassFilter) 用 new 创建对象
staticinitialization(ClassFilter) 匹配类的首次加载
@execution(Attribute) 带有该注解的方法
@access(Attribute) 带有该注解的属性
@within(Attribute) 带有该注解的类的所有成员
matchInherited() 只选中从父类继承或从 trait 导入的成员;!matchInherited() 则排除它们
matchReturningByReference() 声明为 function &name() 的方法和函数;!matchReturningByReference() 则排除它们
$this->pointcutName 在同一个 behavior class 的某个方法上用 #[Pointcut] 声明的具名规则
Aspect\Class->pointcutName 另一个 behavior class 的具名规则

参数列表始终是 (*):参数不参与匹配。

注意分隔符:-> 选中动态方法,:: 选中静态方法。

execution(public App\Service\OrderService->place(*))
execution(public App\Util\Money::format(*))

要拦截对魔术方法的调用,把 behavior 挂接到 __call 本身:

execution(public Foo->__call(*))
模式 含义
* 名称中一个部分内的任意字符(可以为空),从不跨越 \:get*(也匹配 get)、*Service(也匹配 Service)、App\*\Controller(中间恰好一层命名空间)
** 任意命名空间深度:App\** 是 App 之下的所有类,**->*(*) 是所有方法
a|b 名称中一个部分内的备选项,例如 get*|is*。它们只作用于所在的那个部分:App\Cart|Order 表示 App\Cart 或 App\Order,绝不会是全局的 Order。要匹配不同命名空间中的类,用 || 连接两条规则
Foo+ Foo 本身、它的子类和实现类,以及使用 trait Foo 的类(直接使用或通过父类使用)

名称匹配区分大小写。命名空间用单个反斜杠书写;在单引号 PHP 字符串中无需转义。

execution(public **->save*(*))
execution(public App\Repository\*Repository->find*|get*(*))
execution(public App\Contract\Cacheable+->*(*))

方法规则和属性规则接受以下修饰符:

  • public、protected、private
  • final、readonly
  • 非对称可见性修饰符 private(set) 和 protected(set)

用 | 组合备选项:

execution(public|protected App\Service->*(*))

以空格分隔的修饰符必须同时具备,并且 | 的结合优先级高于空格。final public|protected 匹配 public 或 protected 的 final 方法。每个模式只支持一组备选项。

静态属性永远不会被拦截,readonly 属性和已经带有钩子的属性也不会。下文的属性拦截一节列出了所有情况;原因见 限制与升级。

方法或函数模式可以限定声明的返回类型:

execution(public App\Repo->find*(*): App\Entity|null)

联合类型用 |,交叉类型用 &,?Foo 等同于 Foo|null。

运算符 含义
&& 两者都匹配
|| 任一匹配
! 取反
( ) 分组
within(App\**) && !execution(public **->__construct(*))

注释以 // 开头,一直到行尾。在较长的多行表达式中很有用:

#[Around('
execution(public App\Service\**->*(*)) // every public service method
&& !matchReturningByReference() // skip function &name()
&& !matchInherited() // skip inherited and trait methods
')]
public function trace(MethodInvocation $invocation): mixed
{
return $invocation->proceed();
}

一条规则只声明一次,就可以在多个 behavior 中引用:

src/Aspect/HealthyLiveAspect.php
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\After;
use Go\Lang\Attribute\Before;
use Go\Lang\Attribute\Pointcut;
class HealthyLiveAspect implements Aspect
{
#[Pointcut('execution(public App\Human->eat(*))')]
protected function humanEat(): void {}
#[Before('$this->humanEat')]
public function washUpBeforeEat(MethodInvocation $invocation): void { /* ... */ }
#[After('$this->humanEat')]
public function cleanTeethAfterEat(MethodInvocation $invocation): void { /* ... */ }
}

#[Pointcut] 方法的方法体为空;起作用的只有它的注解。在同一个 behavior class 中以 $this->humanEat 引用它。在其他 behavior class 中,使用声明它的类名,例如 App\Aspect\HealthyLiveAspect->humanEat。

@execution、@access 和 @within 按成员所带的 PHP 注解来选中它们。这样你就可以标记应该获得 behavior 的代码,而不是按名称去匹配:

src/Attribute/Cacheable.php
namespace App\Attribute;
#[\Attribute(\Attribute::TARGET_METHOD)]
final class Cacheable {}
src/Aspect/CachingAspect.php
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Around;
class CachingAspect implements Aspect
{
#[Around('@execution(App\Attribute\Cacheable)')]
public function cache(MethodInvocation $invocation): mixed
{
// …
return $invocation->proceed();
}
}

@access(Attribute) 对属性做同样的事,@within(Attribute) 则选中带有该注解的类的所有成员。编译后的类上的注解会连同原始参数一起复制到生成的代码中,因此在运行时读取它们的方式与之前完全一样。缓存行为 正是基于这条规则构建了一个完整的 #[Cacheable(ttl: 600)]。

use Go\Aop\Intercept\FieldAccess;
use Go\Aop\Intercept\FieldAccessType;
use Go\Lang\Attribute\Around;
#[Around('access(public App\Entity\User->email)')]
public function normalizeEmail(FieldAccess $access): mixed
{
if ($access->getAccessType() === FieldAccessType::Write) {
return strtolower($access->proceed());
}
return $access->proceed();
}

access(...) 规则借助生成的代理类上的 PHP 8.4 原生属性钩子(property hooks),拦截对实例属性的读和写。Behavior 会收到一个 FieldAccess。对于写操作,proceed() 返回实际存储的值,因此 Around behavior 可以修改它,就像这个示例那样。

可以被拦截的:

  • 在编译后的类自身中声明的属性,包括构造函数提升的属性(在 PHP 8.5 上也包括 final 的)。构造函数中的赋值会作为一次写操作被拦截。
  • 从父类继承的 public 和 protected 属性

会被跳过的:

  • static、readonly 和已带钩子的属性
  • 从父类继承的 final 属性
  • 继承的 private 属性

对于数组类型的属性,代理只生成一个按引用返回的 &get 钩子,没有 set。这样,像 array_push($this->items, ...) 这样的间接修改依然有效。

Doctrine 在水合或 flush 实体时读写的是原始属性值,因此属性上的 behavior 只会在你自己的代码访问属性时运行。Doctrine 的配置见 集成,概览见 Property hooks 特性页面。

src/Aspect/SerializableAspect.php
use App\Model\JsonSerializableTrait;
use Go\Aop\Aspect;
use Go\Lang\Attribute\DeclareParents;
class SerializableAspect implements Aspect
{
#[DeclareParents('within(App\Model\*)', interfaceName: \JsonSerializable::class, traitName: JsonSerializableTrait::class)]
protected null $jsonSerializable;
}
src/Model/JsonSerializableTrait.php
namespace App\Model;
trait JsonSerializableTrait
{
public function jsonSerialize(): mixed
{
return get_object_vars($this);
}
}

Behavior 改变的是现有类的代码运行时发生什么,而 class extension(类扩展)改变的是这些类对外提供哪些能力。在 behavior class 的一个属性上使用 #[DeclareParents],会给匹配的类加上一个接口,以及一个实现该接口的 trait。这里,App\Model 中的每个类都变成了 JsonSerializable,而无需修改其中任何一个。这同样适用于 Composer 包中的类,见 Class extensions 特性页面。

use Go\Aop\Intercept\FunctionInvocation;
use Go\Lang\Attribute\Around;
#[Around('execution(App\Service\file_get_contents(*))')]
public function logRead(FunctionInvocation $invocation): mixed
{
$this->logger->debug('Reading ' . $invocation->getArguments()[0]);
return $invocation->proceed();
}

execution(App\Service\file_get_contents(*)) 拦截 App\Service 命名空间中的代码对 file_get_contents() 的调用。Behavior 会收到一个 FunctionInvocation。

被拦截函数的代理以 declare(strict_types=1) 生成,每个命名空间一个文件。在进入代理之前,参数已按调用方文件的模式完成类型转换。

use Go\Aop\Intercept\ConstructorInvocation;
use Go\Lang\Attribute\Around;
#[Around('initialization(App\Model\Order)')]
public function trackOrderCreation(ConstructorInvocation $invocation): mixed
{
$order = $invocation->proceed();
// …
return $order;
}

initialization(App\Model\Order) 拦截编译后文件中的 new Order(...)。Behavior 会收到一个 ConstructorInvocation。在对象创建之前,它的 getThis() 返回 null。

staticinitialization(App\Model\*) 在类加载之后运行一次。

Behavior class 是内核容器中的服务。在内核的 configureAop() 中注册它们,最好注册为延迟创建的服务:

app/ApplicationAspectKernel.php
use Aspect\MonitorAspect;
use Go\Core\AspectContainer;
use Go\Core\AspectKernel;
class ApplicationAspectKernel extends AspectKernel
{
protected function configureAop(AspectContainer $container): void
{
// Deferred (recommended): constructed on first use
$container->addLazyService(MonitorAspect::class, static fn() => new MonitorAspect());
// Eager alternative:
// $container->add(MonitorAspect::class, new MonitorAspect());
}
}

addLazyService() 注册的是一个工厂。Compile step(编译步骤)从不实例化 behavior class:每个 behavior class 都在它的某个 behavior 第一次运行时,以 PHP 8.4 原生惰性对象的形式创建。add() 注册的是一个你已经构建好的实例。

工厂会收到内核容器,即一个 AspectContainer。它是一个 PSR-11 容器,所以你可以从中取出 behavior class 的依赖:

use Go\Core\AspectContainer;
use Psr\Log\LoggerInterface;
$container->addLazyService(
ServiceAspect::class,
static fn(AspectContainer $c) => new ServiceAspect($c->getService(LoggerInterface::class)),
);

把应用自己的 PSR-11 容器用 setDelegate() 挂接到内核容器上之后,其中的服务就都可以使用了。Symfony、Laravel 和 Yii3 的框架桥接包会替你注册 behavior class;见 集成。内核选项见 配置与命令行。

无论继承层次中有多少个类被编译,一个 behavior 在每次方法执行中只运行一次。对于编译后的类仅仅继承而来的方法,由规则在那里能匹配到的、最近的已编译祖先类来拦截(最远到声明该方法的类为止);子类继承这个被拦截的方法,不覆写任何东西。

如果不存在这样的祖先类,例如父类位于 includePaths 之外,或者规则不匹配父类,那么就由子类自己拦截这个继承来的方法。

要让规则只作用于类自己声明的成员,加上 !matchInherited()。它会排除从父类继承的成员和从 trait 导入的成员。

有几类方法无法获得 behavior,或者获得之后的工作方式有所不同。完整的列表及原因见 限制与升级。简而言之:

  • 按引用返回。 声明为 function &name() 的方法或函数无法被拦截;编译它会以 WeavingException 失败。用 && !matchReturningByReference() 把这类方法从宽泛的规则中排除。
  • 带 #[\Override] 的 trait 方法。 类从 trait 导入、并且带有 #[\Override] 的方法,无法在该类中被拦截;编译它会以 WeavingException 失败。用 && !matchInherited() 排除它,或者把 behavior 挂接到 trait 本身,例如 execution(public HelloTrait->hello(*)),这样它会在每个使用该 trait 的类中生效。
  • 生成器。 对于包含 yield 的方法,behavior 在方法被调用时运行,proceed() 返回的是 Generator 对象。Behavior 看不到 yield 出来的值。
  • 参数。 getArguments() 按位置列出参数。按引用的可变参数(&...$values)会以传值方式传给原始方法。
  • #[\SensitiveParameter]。 在 call context 和原始方法之间有两个内部栈帧,它们在 Throwable::getTrace() 中仍然持有参数数组。设置 zend.exception_ignore_args=On(生产环境的默认值)后,所有栈帧都不带参数。
  • 属性。 静态属性、readonly 属性和已带钩子的属性不会被拦截,继承的 final 属性和继承的 private 属性也不会。

© 2026 Alexander Lisachenko