Skip to content
Documentation · Integrations

Yii3

Yii3 integration with goaop/goaop-yii3-bridge 1.0: yiisoft/config wiring, tagged behavior classes and ./yii aop:warmup.

The bridge goaop/goaop-yii3-bridge 1.0 plugs into yiisoft/config. Your behavior classes are regular services of the Yii container, and the engine resolves each one only when one of its behaviors first runs.

  • PHP 8.4 or newer
  • Yii3 packages: yiisoft/config, yiisoft/di, yiisoft/aliases (as in the application template)
  • goaop/framework ^4.0 (behaviors declared with attributes)
Terminal window
composer require goaop/goaop-yii3-bridge

The yiisoft/config plugin picks up the configuration of the bridge. If you installed it with the plugin disabled, run composer yii-config-rebuild.

public/index.php
use App\Environment;
use Go\Yii3\GoAopBridge\AopBootstrap;
use Yiisoft\Yii\Runner\Http\HttpApplicationRunner;
// ...
$runner = new HttpApplicationRunner(
rootPath: dirname(__DIR__),
debug: Environment::appDebug(),
checkEvents: Environment::appDebug(),
environment: Environment::appEnv(),
);
AopBootstrap::init($runner->getConfig(), rootPath: dirname(__DIR__));
$runner->run();

Add the AopBootstrap::init() line to every entry script, between the creation of the runner and its run: public/index.php, yii (with its ConsoleApplicationRunner and rootPath: __DIR__), and the bootstrap of your functional tests. It reads the bridge parameters and the aliases from the config of the runner. The runner keeps that config, so the parameters are not built twice.

The compile step only applies to classes loaded after the kernel starts, and the Yii runner autoloads classes while it builds the container. If you skip this line, the bootstrap config group of the bridge still starts the kernel, but late: classes loaded while the container was built are not compiled. In debug mode that includes every class with an array definition, so the application would act differently in development and production.

<?php
declare(strict_types=1);
namespace App\Aspect;
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Around;
use Go\Lang\Attribute\Before;
use Psr\Log\LoggerInterface;
final readonly class LoggingAspect implements Aspect
{
public function __construct(private LoggerInterface $logger) {}
#[Before('execution(public App\Service\**->*(*))')]
public function logCall(MethodInvocation $invocation): void
{
$this->logger->debug('Calling {method}', ['method' => $invocation->getMethod()->getName()]);
}
#[Around('execution(public App\Service\PaymentService->charge(*))')]
public function measureCharge(MethodInvocation $invocation): mixed
{
$start = hrtime(true);
try {
return $invocation->proceed();
} finally {
$this->logger->info('charge() took {ms}ms', ['ms' => (hrtime(true) - $start) / 1e6]);
}
}
}

List the behavior classes in the aspects parameter:

config/common/params.php
'goaop/goaop-yii3-bridge' => [
'aspects' => [
App\Aspect\LoggingAspect::class,
App\Aspect\AuditAspect::class,
],
],

Constructor arguments that can’t be autowired come from a container definition, as for any other service:

use App\Aspect\AuditAspect;
use Yiisoft\Definitions\Reference;
return [
AuditAspect::class => [
'__construct()' => [
'logger' => Reference::to('auditLogger'),
'level' => $params['app']['auditLevel'],
],
],
];

How a behavior class is resolved:

  1. Nothing is autoloaded when the kernel starts: the class names are only validated syntactically.
  2. When the compiler needs the behaviors of a class, it reads them from the class through reflection. The behavior class object is a native lazy proxy and is not constructed yet.
  3. On the first call of one of its behaviors, the proxy is initialized with $container->get(AspectClass::class), the shared instance of the Yii container.

A behavior class that depends on a database connection or an HTTP client doesn’t create it on requests that never reach a method with a behavior. In debug mode the bridge checks that every listed class exists and implements Go\Aop\Aspect.

A package can contribute behavior classes from its own config/params.php. The params group is merged recursively, lists are appended, and duplicates are registered once:

config/params.php
return [
'goaop/goaop-yii3-bridge' => [
'aspects' => [
Vendor\Package\Aspect\CacheAspect::class,
],
],
];

Set 'aspectTag' => 'goaop.aspect'. Then tag the definitions of the common di config group ('tags' => ['goaop.aspect']), or list them in a common di-tags tag map (['goaop.aspect' => [LoggingAspect::class]]). Tagged services must be registered under their class name.

The lookup is off by default because of its cost. The bridge reads the tag declarations from the configuration files before the kernel starts, so every class those files reference (by a class constant or an enum case, for example) is loaded then and can’t be compiled any more. Only the common groups are read. Tags of di-web/di-console definitions, di-tags-web/di-tags-console maps and service providers are not seen.

The defaults live in the params group of the bridge. Override them in config/common/params.php, or per environment in config/environments/<env>/params.php.

Parameter Default Purpose
debug null Recompile when sources or behavior classes change. null follows GOAOP_DEBUG, then APP_DEBUG. Keep it off in production.
appDir '@root' Application root; only files below it are compiled.
cacheDir null Compiled sources, proxies and advisor caches. null follows GOAOP_CACHE_DIR (an alias allowed), then '@runtime/aop'.
cacheFileMode null Permissions of cache files: an integer (0770) or octal digits ('770'). null means 0770 minus the umask.
features 0 Bitmask of Go\Aop\Features flags: PREBUILT_CACHE, PARTIAL_REFLECTION, INTERCEPT_INCLUDES.
includePaths ['@src'] Only these directories are compiled. Keep it narrow.
excludePaths [] Never compiled. The cache directory and the framework are always excluded.
parsedFilesLimit null Parsed files kept in memory while compiling, also the default of aop:warmup --cached-files. null means the kernel default (100).
aspects [] Behavior classes, resolved lazily from the Yii container.
aspectTag null Opt-in container tag that registers behavior classes, e.g. 'goaop.aspect'.

A malformed parameter fails fast with a message naming it. The kernel is available in the container as Go\Core\AspectKernel (and Go\Yii3\GoAopBridge\Kernel\AspectYii3Kernel), its container as Go\Core\AspectContainer. Once the bootstrap callback has run, the kernel’s container delegates unknown ids to the Yii container.

With yiisoft/yii-console installed, the bridge adds these commands to ./yii:

Command Purpose
./yii aop:warmup Compiles every class below the include paths into the cache. --fail-fast, --workers=N, --cache-dir=DIR, --preload[=FILE], --cached-files=N.
./yii aop:opcache Primes the opcache file cache with the framework’s cache, the application and its configuration, after aop:warmup.
./yii aop:debug:aspect Lists the behavior classes with their matching rules and advisors (--aspect=... for one).
./yii aop:debug:advisor Lists the advisors, or what one advisor matches (--advisor=...).
./yii aop:debug:weaving Compiles twice and reports proxies that differ, which reveals circular dependencies between behavior classes and compiled classes.

These are the framework’s own commands, registered in the aop namespace. They run on the kernel the entry line initialized, so leave out their optional loader argument. The workers of --workers=N run ./yii again and need the entry line. When the bootstrap fallback started the kernel, the command compiles in its own process and says so.

Terminal window
./yii aop:warmup --workers=4

In production, turn debug off and build the cache at deploy time. --cache-dir=DIR builds the cache in another directory while the kernel keeps using its own. The cache files are location independent, so you can move the directory into place.

Dockerfile
ENV GOAOP_CACHE_DIR=/app/aop
RUN ./yii aop:warmup --workers=4 --preload

On read-only file systems add Features::PREBUILT_CACHE to features. The engine then trusts the cache completely and never writes to it, so rebuild it on every deploy. A class below the include paths that the cache doesn’t know fails with a Go\Aop\Exception\WeavingException. The aop:warmup process itself is exempt, so it can compile those classes into the cache.

With opcache, ./yii aop:warmup --preload writes _preload.php to the cache directory for opcache.preload, and ./yii aop:opcache primes the file cache in the final image:

Terminal window
mkdir -p /var/cache/opcache && php -d opcache.enable_cli=1 -d opcache.file_cache_only=1 \
-d opcache.file_cache=/var/cache/opcache \
./yii aop:opcache --file-cache=/var/cache/opcache
  • Only classes under appDir and includePaths are compiled. Vendor code is not.
  • Classes loaded before AopBootstrap::init(), such as App\Environment, can’t be compiled. Neither can classes the configuration loads while the entry line reads it.
  • Behavior classes need no compiling themselves: exclude their directory, e.g. 'excludePaths' => ['@src/Aspect'].
  • When creating a behavior class runs one of its own behaviors, that behavior fails with a Go\Aop\Exception\AspectCircularReferenceException. Inject that dependency lazily (a closure or Psr\Container\ContainerInterface), or narrow the matching rule.
  • The kernel is process-global. Long-running workers (RoadRunner, Swoole, FrankenPHP) initialize it once per worker. Reset behavior classes that hold per-request state like any other shared service.

© 2026 Alexander Lisachenko