Symfony
用 goaop/goaop-symfony-bundle 4.0 集成 Symfony:自动配置的 behavior class、Web profiler 面板和缓存预热。
本页译自英文,以英文页面为准。 阅读原文
goaop/goaop-symfony-bundle 4.0 这个 bundle 会在你的服务被加载时,为它们挂上 behavior(行为)。你不需要基类,也不需要装饰器。
namespace App\Aspect;
use Go\Aop\Aspect;use Go\Aop\Intercept\MethodInvocation;use Go\Lang\Attribute\Around;use Psr\Log\LoggerInterface;
final class TimingAspect 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->info('{method} took {ms} ms', [ 'method' => (string) $invocation, 'ms' => (hrtime(true) - $start) / 1e6, ]); } }}集成就这么多。这个类实现了 Go\Aop\Aspect,所以自动配置会把它注册为 behavior class(行为类),自动装配则为它注入 logger。从下一个请求开始,App\Service 下每个类的每个 public 方法都会被计时。
- PHP 8.4 或更高版本
- Symfony 7.4 或 8.x
goaop/framework^4.0(用注解声明 behavior)
安装并启用 bundle
Section titled “安装并启用 bundle”composer require goaop/goaop-symfony-bundle把这个 bundle 注册为 config/bundles.php 中的第一个条目:
return [ Go\Symfony\GoAopBundle\GoAopBundle::class => ['all' => true], Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true], // ...];Compile step(编译步骤)只作用于内核初始化之后加载的类,而 bundle 按注册顺序启动。bundle 会强制保证这一点:如果它不在第一位,容器构建会失败,并给出明确的提示信息。
配置文件是可选的。使用下面的默认值时,bundle 会按内核的模式编译 src/ 目录,并在生产环境中启用预构建缓存:
go_aop: include_paths: ['%kernel.project_dir%/src']
when@prod: go_aop: features: [PREBUILT_CACHE]bin/console config:dump-reference go_aop 会打印完整的配置参考。所有选项及其默认值:
go_aop: # Development mode: changed sources and behavior classes are compiled again on the next request, # breakpoints work in the original files. Keep it off in production. debug: '%kernel.debug%'
# Application root: only files below it can be compiled, cache paths mirror source paths relative to it. app_dir: '%kernel.project_dir%'
# Directory for generated sources, proxies and behavior caches. Anchor it on %kernel.cache_dir% # or %kernel.build_dir% so that cache:clear and cache:warmup manage it. cache_dir: '%kernel.cache_dir%/aop'
# Permissions of the cache files: an octal literal (0o770), an octal string ("0770") or an integer. # Defaults to 0770 minus the umask. cache_file_mode: ~
# Directories that are compiled. Keep the list narrow: compiling vendor code is slow and rarely needed. include_paths: ['%kernel.project_dir%/src']
# Directories below the include paths that are never compiled (the cache directory and the # framework itself are always excluded). exclude_paths: []
# Number of parsed source files the compiler keeps in memory (about 0.2 MB each). parsed_files_limit: 100
# Framework features, by the name of the Go\Aop\Features constant: # PREBUILT_CACHE trust the deployed cache completely, never check or write it at runtime # INTERCEPT_INCLUDES route include/require in compiled files through the compiler (legacy code) # PARTIAL_REFLECTION compile classes whose parent class, interface or trait Composer can not # locate, with their own members features: []
# Kernel class; extend Go\Symfony\GoAopBundle\Kernel\AspectSymfonyKernel to customize # the transformation pipeline. kernel_class: Go\Symfony\GoAopBundle\Kernel\AspectSymfonyKernel
# Compile every file below the include paths during cache:warmup and cache:clear. cache_warmer: true
# Doctrine ORM integration, enabled automatically when DoctrineBundle is registered. doctrine: ~环境变量的用法和在 Symfony 其他地方一样,例如 debug: '%env(bool:GOAOP_DEBUG)%'。函数和 initialization() 这两类 matching rule(匹配规则)不需要功能开关:它们会自行启用所需的机制。
注册 behavior class
Section titled “注册 behavior class”Behavior class 就是一个普通的自动装配服务。自动配置会注册每一个实现了 Go\Aop\Aspect 的服务。没有自动配置时,给服务加上 goaop.aspect 标签:
services: Acme\Audit\AuditAspect: tags: [goaop.aspect]Behavior class 是单例:把它注册为两个服务会导致容器编译错误。
编译器只需要 behavior class 本身。Symfony 容器在 behavior class 的某个 behavior 第一次运行时才创建它,从不在 compile step 或缓存预热期间创建。内核的容器(AspectContainer)也会委托给 Symfony 容器,所以 $aspectContainer->get(LoggerInterface::class) 可以正常工作。Go\Core\AspectKernel 和 Go\Core\AspectContainer 都是可自动装配的服务,goaop.aspect_kernel 是 public 的。
在依赖某个 behavior class 之前,先检查它匹配到了什么:
bin/console debug:aspect # behavior classes with their rules and behaviorsbin/console debug:advisor --advisor='App\Aspect\TimingAspect->measure' # the methods one behavior matches在调试模式下,包含路径(include paths)下的类在首次加载时被编译,当其源码或某个 behavior class 发生变化时会再次编译。
Web profiler 面板
Section titled “Web profiler 面板”安装 symfony/web-profiler-bundle 后,工具栏会显示 behavior class 的数量。Go! AOP 面板会列出:
- Behavior class 及其 advisor、behavior 注解和 matching rule;
- 请求期间加载的被编译类,以及它们的代理文件;
- 包含路径下在内核初始化之前就已加载的类(此时面板会变成黄色);
- 内核的实际生效配置。
第三个列表用来诊断两种情况:某个 bundle 在 GoAopBundle 之前启动,以及重建容器的那一个请求。那个请求必须在 bundle 启动之前加载服务类,所以这些类会有一次在不带 behavior 的情况下运行。下一个请求就会完全以编译后的形式运行。部署不受影响,因为 cache:clear 和 cache:warmup 会同时构建容器和框架的缓存。
除非你的配置显式设置了 Symfony 的 .container.dumper.inline_class_loader,bundle 还会把它关掉。这个选项会直接 include 服务文件,从而绕过类加载器,也就绕过了 compile step。
composer install --no-dev --optimize-autoloader # runs cache:clear through the auto-scripts# or explicitlybin/console cache:clearbin/console cache:warmupcache:clear 和 cache:warmup 通过一个缓存预热器(cache warmer)编译整个应用。cache:clear 会在运行中的缓存旁边构建新缓存,之后再重命名过去。预热器在这个新目录中从头构建框架的缓存,所以你平常的部署步骤无需任何改动。有文件无法编译时预热会失败,部署就此停下,而不会发布一个不完整的缓存。运行 cache:warmup:aop --fail-fast -vvv 可以看到具体的文件和错误。
框架的命令会注册到你应用的控制台中。它们作用于正在运行的内核,所以省略 vendor/bin/aspect 的 loader 参数。
| 命令 | 用途 |
|---|---|
cache:warmup:aop [--fail-fast] [--cache-dir=DIR] [--cached-files=N] [--preload[=FILE]] |
把包含路径下的每个文件编译进缓存。有文件无法编译时失败。--preload 还会写出该缓存的 opcache.preload 脚本。 |
cache:warmup:opcache [--file-cache=DIR] [--entry=FILE] |
用框架的缓存和应用预先填充 opcache 文件缓存(opcache.file_cache)。在最终镜像中运行。 |
debug:aspect [--aspect=FQCN] |
列出 behavior class 及其 matching rule 和 advisor。 |
debug:advisor [--advisor=ID] |
列出 advisor;加上 --advisor 时,列出该 advisor 匹配到的内容。 |
debug:weaving [-v] |
把应用编译两次,并报告不一致的代理,这意味着某个 behavior class 是非确定性的。 |
在这里,cache:warmup:aop --workers=N 只会在一个进程中编译:它的 worker 进程需要通过 loader 文件启动内核,而应用的控制台没有这样的文件。
生产环境设置
Section titled “生产环境设置”when@prod: go_aop: features: [PREBUILT_CACHE]启用 PREBUILT_CACHE 后,运行时会跳过所有与缓存相关的文件系统检查,从不编译,也从不写入缓存目录。缓存中没有记录的、位于包含路径下的类会以 WeavingException(“… is missing from the prebuilt AOP cache …”)失败。每次部署都要重建缓存。这是推荐的生产环境设置,它让只读文件系统和不可变镜像都能正常工作。
如果你的 kernel.build_dir 与 kernel.cache_dir 不同,就把框架的缓存放在你部署时构建的那个目录下:cache_dir: '%kernel.build_dir%/aop'。
使用 opcache 预加载时,先 require 框架缓存的预加载脚本,再 require 容器的预加载文件:
if (is_file($aop = dirname(__DIR__).'/var/cache/prod/aop/_preload.php')) { require $aop;}if (is_file($container = dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php')) { require $container;}在生产模式下,缓存预热器会把 _preload.php 写入框架的缓存目录。当 cache_dir 不是 %kernel.cache_dir%/aop 时,相应调整它的路径。不要在 config/preload.php 中启动内核:那样会以 “Cannot redeclare class” 失败。关于生产构建的更多内容,见 生产环境与性能。
在 Symfony 中使用 Doctrine ORM
Section titled “在 Symfony 中使用 Doctrine ORM”当注册了 DoctrineBundle,或者你设置了 doctrine: true 时,bundle 会:
- 把每个由 ORM 注解驱动的目录扫描替换为
Go\Bridge\Doctrine\WovenEntityClassLocator,它通过类加载器加载实体,因此实体会保留自己的 behavior; - 把
Go\Bridge\Doctrine\MetadataLoadInterceptor注册为loadClassMetadata监听器,在原生惰性对象关闭时,于元数据加载阶段报告被拦截的实体属性。
实体必须位于某个包含路径下才会被编译。这样一来,无论实体是由你的代码创建,还是由 ORM 水合(hydrate)出来,它们的 behavior 都会生效。Doctrine ORM 页面介绍了这两个类。
-
Behavior 没有生效。 先运行
debug:advisor --advisor=...:它会列出 matching rule 选中了哪些内容。然后检查这个类是否位于某个包含路径下,并且没有在 bundle 启动之前就被加载(见 profiler 面板中的 classes loaded before weaving)。vendor 代码只有在其目录是包含路径时才会被编译。 -
“Class … is missing from the prebuilt AOP cache”。 部署发布的代码不是这份缓存构建时所针对的代码。在代码就位之后运行
bin/console cache:clear(或cache:warmup)。 -
“Circular reference detected for the aspect …”。 创建 behavior class 的某个依赖时,运行了同一个类的某个 behavior。惰性注入这个依赖,或者收窄 matching rule:
public function __construct(#[Autowire(lazy: true)] private readonly Wallet $wallet, // or #[AutowireServiceClosure(Wallet::class)], a service locator) {} -
“Class … was not found by locator”。 包含路径下的某个类继承了 Composer 无法定位的代码,例如一个生成的基类。让 Composer 能够定位它、启用
PARTIAL_REFLECTION,或者用exclude_paths排除依赖它的类。 -
异常处理器。 通过
exclude_paths排除那些在其他一切都失败时仍必须加载的类(错误处理器、内核)。
© 2026 Alexander Lisachenko
