改变已有代码执行时发生的事。
#[Around('@execution(App\Attribute\Cacheable)')]方法保持原有签名。行为在每次调用周围运行:缓存、日志、事务。
拦截一切
在一个地方,为 pointcut(切入点)选中的每个类添加接口及其实现。
你的导出流水线接受任何 Exportable。支付 SDK 的 DTO 并没有实现它,而且它们是 final 的。与其 fork 这个包,或为每个 DTO 包一层适配器,不如用一个行为类为它们全部加上你的接口和一个可复用的 trait。
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;
你的 trait
}
更多内容见 docs/advices.md 和 docs/configuration.md。
包保持 Composer 安装时的原样。更新照常通过 composer update 到来,下一次缓存预热会再次织入它们。
类保留它的名称、修饰符和父类。接口和 trait 加在这个类本身上,而不是加在子类上。
instanceof 和类型声明都能正常工作,因为 PHP 加载的类确实实现了这个接口。