其他框架与纯 PHP
适用于任意 PHP 框架,或不用框架:自己编写内核,让 behavior class 从 PSR-11 容器中获取依赖。
本页译自英文,以英文页面为准。 阅读原文
没有桥接包时,你需要自己编写内核,并在前端控制器中初始化它,做法见 快速上手。要让 behavior class(行为类) 访问应用中的服务,把应用的 PSR-11 容器挂接为内核容器(AspectContainer)的委托容器:
protected function configureAop(AspectContainer $container): void{ // Runs when one of its behaviors first runs, after the application container is attached $container->addLazyService( MonitorAspect::class, static fn(AspectContainer $container) => new MonitorAspect($container->getService(LoggerInterface::class)), ); // or take the whole behavior class from the application container, by the id it has there // $container->addLazyService(MonitorAspect::class, static fn(AspectContainer $c) => $c->get('app.monitor_aspect'));}// Once the application container exists, e.g. right after the framework kernel has bootedApplicationAspectKernel::getInstance()->getContainer()->setDelegate($psrContainer);对于自己不认识的 id,内核容器的 get()、getService() 和 has() 会转而查询委托容器。内核在应用构建容器之前就已初始化,因此你照常注册 behavior class,它们的依赖会被惰性解析。Compile step(编译步骤)和缓存预热只需要 behavior class 本身,所以它们在 setDelegate() 之前运行,并且从不创建它的实例。如果工厂运行时某个依赖仍然缺失,会抛出 ServiceNotFoundException。
- 工厂永远不要向内核容器请求它自己的 id:这个 id 解析出来的正是当前正在构建的 behavior class。
- Behavior class 永远不会从委托容器中被发现,因为 PSR-11 容器无法被内省。请在
configureAop()中注册每一个 behavior class。针对特定框架的桥接包可以按标签或接口收集服务,再用addLazyService()注册它们。 - 创建 behavior class 时不能触发它自己的任何一个 behavior(行为)。拦截器会用
AspectCircularReferenceException报告这种情况。
所有内核选项、Features 开关和 vendor/bin/aspect 命令见 配置与命令行。部署方案见 生产环境与性能。
© 2026 Alexander Lisachenko
