既存のコードの実行時に起きることを変える。
#[Around('@execution(App\Attribute\Cacheable)')]メソッドのシグネチャはそのままです。キャッシュ、ロギング、トランザクションといった振る舞いが、すべての呼び出しの周りで動きます。
何でもインターセプト
ポイントカットが選ぶすべてのクラスに、インターフェースとその実装を 1 か所から追加します。
どちらも振る舞いクラス(API ではアスペクト)で宣言し、どちらもソースファイルには手を触れません。
#[Around('@execution(App\Attribute\Cacheable)')]メソッドのシグネチャはそのままです。キャッシュ、ロギング、トランザクションといった振る舞いが、すべての呼び出しの周りで動きます。
何でもインターセプト#[DeclareParents('within(Acme\Payments\Dto\*)', …)]クラスがインターフェースと、トレイトのメソッドを得ます。既存の呼び出しの周りでは何も動きません。新しいメソッドを呼ぶのはあなたのコードです。
例を見るエクスポートのパイプラインは Exportable なものなら何でも受け付けます。決済 SDK の DTO はそうではなく、しかも final です。パッケージをフォークしたり、すべての DTO をアダプターで包んだりする代わりに、1 つの振る舞いクラスが、そのすべてにインターフェースと再利用できるトレイトを追加します。
interface Exportable{ /** @return array<string, scalar|null> */ public function toExportRow(): array;} // src/Export/ExportsPublicProperties.phptrait ExportsPublicProperties{ public function toExportRow(): array { return get_object_vars($this); }}パッケージを includePaths に指定すると、自分のコードと同じようにウィービングされます。ベンダーのコードのウィービングはウォームアップの時間を使うので、拡張するパッケージだけを挙げてください。
AppKernel::getInstance()->init([ // … 'includePaths' => [ __DIR__ . '/src', __DIR__ . '/vendor/acme/payments-sdk/src', ],]);$charge = new Charge('ch_1', 4200, 'EUR'); // a vendor DTO $charge instanceof Exportable; // true$exporter->write($charge); // accepts any Exportable$charge->toExportRow(); // ['id' => 'ch_1', 'amount' => 4200, 'currency' => 'EUR']
<?php
declare(strict_types=1);
namespace Acme\Payments\Dto;
final readonly class Charge
final かつ readonly
{
public function __construct(
public string $id,
public int $amount,
public string $currency,
) {}
}
<?php
declare(strict_types=1);
namespace App\Aspect;
use App\Contract\Exportable;
use App\Export\ExportsPublicProperties;
use Go\Aop\Aspect;
use Go\Lang\Attribute\DeclareParents;
final class ExportAspect implements Aspect
{
#[DeclareParents('within(Acme\Payments\Dto\*)', interfaceName: Exportable::class, traitName: ExportsPublicProperties::class)]
パッケージの全 DTO
protected null $exportable;
}
<?php
declare(strict_types=1);
namespace Acme\Payments\Dto;
use Go\Aop\Framework\InterceptorInjector;
use Go\Aop\Framework\Interceptor;
use Go\Aop\Framework\The;
final readonly class Charge implements \App\Contract\Exportable, \Go\Aop\Proxy
あなたのインターフェース
{
use ChargeOriginalTrait, \App\Export\ExportsPublicProperties;
あなたのトレイト
}
詳しくは docs/advices.md と docs/configuration.md を参照してください。
パッケージは Composer がインストールしたままです。更新は composer update でこれまでどおり届き、次のキャッシュのウォームアップで改めてウィービングされます。
クラスは名前、修飾子、親クラスを保ちます。インターフェースとトレイトは、サブクラスではなく、そのクラス自体に追加されます。
PHP が読み込むクラスが実際にインターフェースを実装しているので、instanceof も型宣言も機能します。