コンテンツにスキップ
ドキュメント

振る舞いとマッチングルール

フレームワークがコードの周りで実行する動的な middleware である behavior の書き方と、それをどこに適用するかを決める matching rule の完全なリファレンスです。

このページは英語版からの翻訳です。基準となるのは英語版のページです。 原文を読む

このページでは、フレームワークを使うときに書くものをすべて扱います。behavior class(振る舞いクラス)、その中でコードの周りに動的な middleware(ミドルウェア)として実行される behavior(振る舞い)、各 behavior が受け取る call context(呼び出しコンテキスト)、そして behavior をどこで実行するかを選ぶ 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] のいずれか 1 つを持つもの
Matching rule(マッチングルール) Pointcut(ポイントカット) その属性に書く式で、behavior をどこで実行するかを選ぶもの
Call context(呼び出しコンテキスト) Joinpoint(ジョインポイント) インターセプトされた瞬間(メソッド呼び出し、プロパティへのアクセス、オブジェクトの生成)で、オブジェクトとして behavior に渡されるもの
Compile step(コンパイルステップ) Weaving(ウィービング) behavior を付け加えたうえで、クラスを PHP が読み込むファイルに変換する処理
Class extension(クラス拡張) Introduction(イントロダクション) 既存のクラスに追加されるインターフェースとトレイト
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 は、その matching rule が選ぶコードの周りで middleware として実行されます。上の例では、measure() が App\Service のすべての public メソッドを包み、logFailure() はそのいずれかが例外を投げたときに実行されます。普通のクラスなので、コンストラクターインジェクション、private な状態、トレイトなど、PHP が提供するものは何でも使えます。

behavior が実行されるタイミング

Section titled “behavior が実行されるタイミング”

behavior に付ける属性は、インターセプトされた呼び出しに対して、いつ実行されるかを示します。

属性 実行されるタイミング
#[Before] 呼び出しの前。setArguments() で引数を変更できます。
#[After] 呼び出しの後。例外が投げられた場合も実行されます(finally と同様)。
#[AfterThrowing] 呼び出しが例外を投げたとき。2 番目の引数として例外を受け取り、その後で例外は再スローされます。
#[Around] 呼び出しの代わりに、middleware と同じように。proceed() を呼ぶかどうかを自分で決め、その戻り値が結果になります。

4 つの属性はいずれも 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 は、呼び出しが例外を投げたときにだけ実行されます。2 番目の引数として例外を受け取ります。フレームワークは 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 動的メソッドと static メソッドの 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 になる仕組み

Section titled “behavior が middleware になる仕組み”

behavior を付け加える仕組みに魔法はありません。インターセプトされる各メソッドに対して、フレームワークは素の middleware チェーンを生成します。各 behavior は、behavior class のインスタンスに対して first-class callable 構文で作られたクロージャーとして参照されます。

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 をどこで実行するかを選ぶ式です。対象はメソッドの実行、プロパティへのアクセス、関数の呼び出し、オブジェクトの生成です。matching rule は behavior の属性の引数として書きます。

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

プレイグラウンドでは PHP ファイルに対してルールを試せます。このセクションは完全なリファレンスです。

ルール 選ぶもの
execution(modifiers Class->method(*)) 動的メソッドの実行
execution(modifiers Class::method(*)) static メソッドの実行
execution(Namespace\function(*)) その名前空間からのシステム関数の呼び出し
access(modifiers Class->property) インスタンスプロパティの読み取りと書き込み
within(ClassFilter) マッチしたクラスのすべてのメンバー(メソッドとプロパティ)
initialization(ClassFilter) new によるオブジェクトの生成
staticinitialization(ClassFilter) マッチしたクラスの最初の読み込み
@execution(Attribute) その属性を持つメソッド
@access(Attribute) その属性を持つプロパティ
@within(Attribute) その属性を持つクラスのすべてのメンバー
matchInherited() 親クラスから継承したメンバー、またはトレイトから取り込んだメンバーだけ。!matchInherited() はそれらを除外します
matchReturningByReference() function &name() と宣言されたメソッドと関数。!matchReturningByReference() はそれらを除外します
$this->pointcutName 同じ behavior class のメソッドに #[Pointcut] で宣言した名前付きルール
Aspect\Class->pointcutName 別の behavior class の名前付きルール

引数リストは常に (*) です。引数はマッチングの対象になりません。

区切り記号に注意してください。-> は動的メソッドを、:: は static メソッドを選びます。

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

マジックメソッドの呼び出しをインターセプトするには、behavior を __call そのものに付けます。

execution(public Foo->__call(*))
パターン 意味
* 名前の 1 つの部分に含まれる任意の文字(0 文字を含む)で、\ をまたぐことはありません。get*(get も含む)、*Service(Service も含む)、App\*\Controller(間にちょうど 1 階層の名前空間)
** 任意の深さの名前空間。App\** は App の下のすべてのクラス、**->*(*) はすべてのメソッドです
a|b 名前の 1 つの部分の中での選択肢です。例:get*|is*。選択肢は書かれた部分にだけ適用されます。App\Cart|Order は App\Cart か App\Order で、グローバルな Order には決してなりません。異なる名前空間のクラスを対象にするには、2 つのルールを || でつなぎます
Foo+ Foo 自身、そのサブクラスと実装クラス、そしてトレイト Foo を(直接または親クラスを通じて)使うクラス

名前は大文字と小文字を区別してマッチします。名前空間はバックスラッシュ 1 つで書きます。シングルクォートの 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 メソッドにマッチします。1 つのパターンで使える選択肢のグループは 1 つです。

static プロパティはインターセプトされません。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 ネイティブのプロパティフックを通して、インスタンスプロパティの読み取りと書き込みをインターセプトします。behavior は FieldAccess を受け取ります。書き込みの場合、proceed() は格納される値を返すので、この例のように Around の behavior でその値を変更できます。

インターセプトできるもの:

  • コンパイルされるクラス自身で宣言されたプロパティ。コンストラクターのプロモーションによるプロパティも含みます(PHP 8.5 では final のものも)。コンストラクターによる代入は書き込みとしてインターセプトされます。
  • 親クラスから継承した public と protected のプロパティ

スキップされるもの:

  • static、readonly、すでにフックを持つプロパティ
  • 親クラスから継承した final プロパティ
  • 継承した private プロパティ

配列型のプロパティについては、プロキシは参照渡しの &get フックだけを出力し、set は出力しません。これにより、array_push($this->items, ...) のような間接的な変更が有効なまま保たれます。

Doctrine はエンティティのハイドレートやフラッシュの際に生のプロパティ値を読み書きするため、プロパティに対する behavior は、あなた自身のコードによるアクセスでのみ実行されます。Doctrine の設定はインテグレーションを、概要はプロパティフックの機能ページを参照してください。

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] は、マッチしたクラスにインターフェースと、それを実装するトレイトを追加します。この例では、App\Model のすべてのクラスが、どれも編集することなく JsonSerializable になります。これは Composer パッケージのクラスにも使えます。クラス拡張の機能ページを参照してください。

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) 付きで、名前空間ごとに 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 ネイティブの lazy オブジェクトとして生成されます。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 を自動で登録します。インテグレーションを参照してください。カーネルのオプションは設定と CLI で扱います。

behavior は、階層内のいくつのクラスがコンパイルされていても、メソッドの実行 1 回につき一度だけ実行されます。コンパイルされたクラスが継承しているだけのメソッドは、そのメソッドに対してルールがマッチする最も近いコンパイル済みの祖先(そのメソッドを宣言しているクラスまで)でインターセプトされます。サブクラスはインターセプトされたそのメソッドを継承し、何もオーバーライドしません。

そのような祖先が存在しない場合、たとえば親クラスが includePaths の外にある場合や、ルールが親クラスにマッチしない場合は、サブクラス自身が継承したメソッドをインターセプトします。

ルールの対象をクラス自身が宣言しているメンバーに限るには、!matchInherited() を加えます。これは親クラスから継承したメンバーと、トレイトから取り込んだメンバーを除外します。

いくつかの種類のメソッドには behavior を付けられないか、付けた場合に動作が異なります。理由を含む完全な一覧は制限事項とアップグレードにあります。要点は次のとおりです。

  • 参照返し。 function &name() と宣言されたメソッドや関数はインターセプトできません。コンパイルは WeavingException で失敗します。広いルールからそのようなメソッドを除外するには && !matchReturningByReference() を使います。
  • #[\Override] 付きのトレイトメソッド。 クラスがトレイトから取り込み、#[\Override] を持つメソッドは、そのクラスではインターセプトできません。コンパイルは WeavingException で失敗します。&& !matchInherited() で除外するか、behavior をトレイトそのものに付けてください。たとえば execution(public HelloTrait->hello(*)) は、そのトレイトを使うすべてのクラスに適用されます。
  • ジェネレーター。 yield を含むメソッドでは、behavior はメソッドが呼び出されたときに実行され、proceed() は Generator オブジェクトを返します。behavior から yield された値は見えません。
  • 引数。 getArguments() は引数を位置の順に並べます。参照渡しの可変長引数(&...$values)は、元のメソッドには値渡しで渡されます。
  • #[\SensitiveParameter]。 call context と元のメソッドの間にある 2 つの内部フレームは、Throwable::getTrace() の中に引数の配列をまだ保持しています。本番環境のデフォルトである zend.exception_ignore_args=On では、どのフレームも引数を持ちません。
  • プロパティ。 static、readonly、すでにフックを持つプロパティはインターセプトされません。継承した final プロパティや、継承した private プロパティも同様です。

© 2026 Alexander Lisachenko