Skip to content
Documentation

Limitations & Upgrading to 4.0

What version 4.0 cannot intercept and how to work around it, followed by the complete migration guide from 3.x.

This page has two halves. The first lists what version 4.0 does not intercept, why, and what to do instead. The second is the full migration guide from 3.x to 4.0, in the order you should apply it.

The limitations are stated as they are. Most come from PHP itself, and each one fails in a predictable way: either the compiler throws a WeavingException at compile time, or the member is skipped.

Methods and functions that cannot be intercepted

Section titled “Methods and functions that cannot be intercepted”

A method or function declared function &name() cannot be intercepted. Call contexts and behaviors return values, so the caller would get a copy instead of the reference. Compiling one fails with a WeavingException.

Exclude such methods from a broad matching rule with !matchReturningByReference():

#[Around('execution(public App\Service\*->*(*)) && !matchReturningByReference()')]

In 3.x the call context returned a copy with a notice. In 4.0 it is an error, so you find these methods at compile time.

A method that a class imports from a trait and that carries #[\Override] cannot be intercepted in that class. PHP copies the attribute to the private alias the proxy calls, and that alias overrides nothing. Compiling one fails with a WeavingException.

You have four options:

  • Exclude trait methods from the rule with && !matchInherited().
  • Exclude only that method, for example && !execution(public Foo->hello(*)).
  • Remove #[\Override] from the trait.
  • Target the trait itself, for example execution(public HelloTrait->hello(*)). The trait is compiled, which works with #[\Override], and the behavior applies in every class using the trait.

Trait methods that a class inherits from its parent class are not affected.

For a method that contains yield, the behavior runs when the method is called, and proceed() returns the Generator object. The behavior does not see the yielded values: they are produced later, while the caller iterates.

getArguments() lists the arguments by position. A by-reference variadic parameter (&...$values) is passed to the original method by value.

The proxy keeps the attribute. The framework frames that carry the arguments as an array hide them: the call context’s __invoke(), the generated __initialization() and the rewritten new.

Two internal functions between the call context and the original method cannot hide them:

  • ReflectionMethod::invokeArgs(), for instance methods and constructors
  • forward_static_call_array(), for static methods

Their frames in Throwable::getTrace() still hold the argument array, which the text form of the trace prints as Array. Error trackers that collect frame arguments see it. With zend.exception_ignore_args=On, the production default, no frame has arguments.

The proxies of intercepted functions are generated with declare(strict_types=1), one file per namespace. The arguments are coerced by the calling file’s mode before the proxy is entered.

access(...) rules intercept reads and writes of instance properties through native PHP 8.4 property hooks on the generated proxy: the generated hooks route reads and writes through ClassFieldAccess call contexts. See property interception for what this gives you. The following properties are intentionally skipped:

Property Why
static properties PHP has no property hooks for static properties. This is an engine constraint.
readonly properties, including public private(set) readonly PHP does not allow hooks on readonly properties.
Properties that already have get or set hooks The framework cannot compose its hooks with hooks you defined.
Inherited final properties from parent classes Not supported.
Inherited private properties Not supported.

Supported targets are the properties declared in the compiled class itself, including constructor-promoted properties, and inherited public and protected properties from parent classes.

A skipped property does not raise an error. If your rule matches it, the property is silently left out of interception: AdviceMatcher skips static, readonly and hooked properties before any proxy code is generated. The property generator also refuses such a property with a WeavingException as a safety net.

Asymmetric visibility on non-readonly properties is preserved. public protected(set) string $name keeps its modifiers in the proxy class.

The framework builds property interception on PHP 8.4 property hooks, and its container uses PHP 8.4 lazy objects for deferred services. Two parts of this have limits.

Lazy object initialization cannot be intercepted

Section titled “Lazy object initialization cannot be intercepted”

PHP 8.4 introduced ReflectionClass::newLazyProxy() and ReflectionClass::newLazyGhost() for lazy object initialization. The framework’s Container uses native lazy proxies for its own deferred services and for behavior classes registered by class name. Retrieving such a service hands out a typed, instanceof-correct newLazyProxy() instance. The registered factory runs only on the first real interaction with that object.

Classes PHP cannot make lazy fall back to eager construction: internal classes and their non-stdClass subclasses, abstract classes and enums.

There is no call context for the moment a lazy proxy materializes its backing instance, so lazy object initialization itself cannot be intercepted.

PHP 8.4 feature Support Notes
Property hooks on new properties Generated by the framework Used for access(...) interception
Properties with existing hooks Skipped The framework cannot compose with user-defined hooks
Readonly properties Skipped Hooks are not allowed on readonly properties
Asymmetric visibility (non-readonly) Preserved Visibility modifiers are copied to the proxy
#[\Deprecated] attribute Propagated Copied to proxy methods and classes
Lazy objects (newLazyProxy) Not interceptable No call context for lazy initialization

The PHP 8.5 notes are based on an audit of the framework on PHP 8.5.10 and PHP 8.6.0beta2.

  • Pipe operator |>. It works inside compiled method bodies. Method bodies are moved verbatim into the <Class>OriginalTrait body trait, so any PHP 8.5 expression syntax inside them is preserved.
  • clone with. Expressions in compiled code work as expected.
  • #[\NoDiscard]. The attribute is copied to the generated proxy method, and the call context returns the intercepted method’s value. The engine’s “return value not used” warning keeps firing for compiled methods.
  • Attributes on class constants, including #[\Deprecated]. Class constants stay in the generated trait together with their attributes.
  • Closures and first-class callables as parameter defaults. They survive compilation in proxy method signatures.
  • Static asymmetric visibility. static properties with asymmetric visibility (public static private(set)) work on compiled classes. They are never targeted by access(...) rules.
  • self and parent reflection resolution. On PHP 8.5, ReflectionNamedType::getName() resolves self and parent return types to concrete class names. The proxy generators read the raw AST type node where available, so the self and parent keywords are preserved in generated proxies.

A new expression in a constant expression is evaluated by the engine. That covers the default value of a parameter or of a promoted constructor parameter, a static variable initializer and an attribute argument. The compiler leaves these expressions as they are, so the code works, but an initialization(...) behavior does not run for the objects they create. Only new expressions in executable code are intercepted.

Static properties, including PHP 8.5 static properties with asymmetric visibility, cannot be intercepted with access(...) rules. PHP property hooks do not exist for static properties, so the framework has no interception mechanism for them, and AdviceMatcher excludes them from property interception. This is a PHP engine constraint, not a bug.

PHP 8.5 feature Support Notes
Pipe operator |> in method bodies Works Bodies are moved verbatim into the generated trait
clone with Works
#[\NoDiscard] Propagated Copied to the proxy; the call context returns the value
Attributes on class constants (including #[\Deprecated]) Preserved Constants stay in the generated trait
Closures and first-class callables as parameter defaults Works
Static asymmetric visibility (non-intercepted) Preserved Static properties are never interceptable with access()
self/parent reflection resolution Handled Raw AST type nodes are used in proxy generation
new in initializers Not intercepted Evaluated by the engine; initialization(...) behaviors do not run for it
Static property interception with access() Never No property hooks for static properties (PHP engine constraint)

Only classes loaded after the kernel is initialized are compiled. A class that is loaded before that point runs without its behaviors. Initialize the kernel as early as possible in your front controller. Framework bridges must boot first; see Integrations for how each bridge handles it.

The argument list in a matching rule is always (*). A rule selects methods by class, name, modifiers, return type and attributes, never by argument values or parameter types. To act on specific arguments, match the method and inspect $invocation->getArguments() inside the behavior. The full syntax is in Behaviors & Matching Rules.

These numbers come from the framework’s own benchmark in docs/performance.md: a small shop application with about 250 files, 94 compiled classes and 6 behavior classes, on PHP 8.5.12 with JIT disabled. The file explains how they were measured and how to reproduce them.

While an initialization rule is registered, every new in the generated files goes through the transformer. A class without initialization behaviors (and with a public constructor) is still created by a native new, which costs roughly 130 ns more than a plain new. A class with initialization behaviors goes through the full call context. Prefer method rules where they do the job.

With 'debug' => true, generated classes are served through the stream filter, so Xdebug breakpoints and magic constants point at your original files, and changed files are recompiled automatically. In the benchmark, hot requests in debug mode take more than twice as long as in production mode. Use 'debug' => false in production; see Production.

Version 4.0 replaces the inheritance-based compiler with a trait-based one, generates behaviors as first-class callables, and rebuilds the caches for PHP 8.4. Most applications only need the checklist below. The sections after it describe every breaking change. The API names in them keep the classic terms; the terms table maps them to the words used here. The full list of changes is in the CHANGELOG.

  1. Run on PHP 8.4 or newer and update the dependencies (see Requirements and dependencies below).

  2. Make every behavior method of your behavior classes public (see Behavior classes below).

  3. Register behavior classes with add() or addLazyService() instead of registerAspect().

  4. Replace ? wildcards in matching rules with *, and rewrite dynamic(...) rules.

  5. Delete the cache directory, then warm it up again. The argument is the file that initializes your kernel:

    Terminal window
    vendor/bin/aspect cache:warmup:aop public/index.php
  6. If you use the Doctrine bridge, switch entity discovery to WovenEntityClassLocator.

  • PHP 8.4+ with ext-tokenizer.
  • Update the dependencies with Composer. The required versions are listed in composer.json.
  • psr/container is a new dependency, and nikic/php-parser is installed through goaop/parser-reflection.
  • laminas/laminas-code is no longer used. Proxies are generated by the internal Go\Proxy\Generator package. Code that extended the framework generators, or relied on laminas generator classes coming with the framework, has to be updated.
  • bin/aspect needs symfony/console.

Every cache format changed, and no 3.x cache file is reused.

  • Proxy layout. The _proxies subdirectory is gone. A proxy is stored at the relative path of its source file below the cache directory, and the generated source (the original class body as a <Class>OriginalTrait trait) next to it.
  • Class map. _include.cache maps every compiled class to its cached file and is handed to Composer at boot. It also maps every known source file to its cached file (or null when untransformed) for the includes intercepted by INTERCEPT_INCLUDES. A cache directory without it is treated as stale.
  • Behavior-class cache. The serialized {cacheDir}/_aspect/sha1(FQCN) blobs are replaced by plain PHP files next to the generated sources: {appDir}/src/Aspect/LoggingAspect.php is cached as {cacheDir}/src/Aspect/LoggingAspect.cache.php. Interceptors are no longer serializable: AbstractInterceptor::__serialize(), __unserialize(), serializeAdvice() and unserializeAdvice() are removed.

The metadata files carry a format version. With Features::PREBUILT_CACHE, a cache built by another framework version is rejected with an exception instead of being rebuilt at runtime.

Features::PREBUILT_CACHE now trusts the cache completely. Directory and writability probes, filemtime comparisons, tracked-resource checks and freshness checks of the behavior-class caches are all skipped. Rebuilding the cache on deploy is the deployer’s responsibility.

The cacheFileMode option is validated. It must be an integer between 0600 and 0777 that grants the owner read and write access. Directories get search permissions matching the read bits of the mode.

Generated proxies call behaviors as first-class callables on the behavior class instance. A method with #[Before], #[After], #[Around] or #[AfterThrowing] must therefore be public. The loader throws an AspectException for protected or private behavior methods. Methods that only carry #[Pointcut] may keep any visibility.

3.x
#[Before('execution(public Example->*(*))')]
protected function beforeMethod(MethodInvocation $invocation): void {}
// 4.0
#[Before('execution(public Example->*(*))')]
public function beforeMethod(MethodInvocation $invocation): void {}

A method of a behavior class carries at most one of #[Before], #[After], #[Around] and #[AfterThrowing]. A second one throws an AspectException. Split such a method into one method per behavior. #[Pointcut] may still be combined with a behavior attribute on the same method, and attributes that do not belong to the framework are ignored.

AspectContainer::registerAspect() is removed. Behavior classes are ordinary container services.

Before, in 3.x:

app/ApplicationAspectKernel.php
// 3.x
protected function configureAop(AspectContainer $container)
{
$container->registerAspect(new MonitorAspect());
}

After, in 4.0:

app/ApplicationAspectKernel.php
// 4.0
protected function configureAop(AspectContainer $container): void
{
// Deferred (recommended): constructed when one of its behaviors runs for the first time
$container->addLazyService(MonitorAspect::class, static fn() => new MonitorAspect());
// Eager alternative
// $container->add(MonitorAspect::class, new MonitorAspect());
}

addLazyService() stores a factory and builds the service on its first retrieval. Code that expected a lazy-proxy instance to exist at boot must call getService(). A factory returning an object of the wrong type now fails on first use, not at registration.

AspectContainer::addResource() is part of the interface. onRegistration() lets you react to deferred registrations of services implementing an interface.

AspectContainer extends Psr\Container\ContainerInterface, so you can pass the container to any code that expects a PSR-11 container.

  • AspectContainer::getValue() is renamed to get().
  • has() comes from the PSR interface, with the same signature.
  • A custom containerClass implements get() instead of getValue(), plus setDelegate(), which attaches the container of your application. See Configuration.
4.0
// before
$pointcut = $container->getValue('my.pointcut');
$pointcut = $container->get('my.pointcut');

An unknown id throws ServiceNotFoundException, which implements Psr\Container\NotFoundExceptionInterface. getService() throws Go\Aop\Exception\ContainerException when the entry is not an instance of the requested class. That exception is an InvalidConfigurationException implementing Psr\Container\ContainerExceptionInterface.

The rename applies to the container only. FieldAccess::getValue() on property call contexts is unchanged.

  • The AdviceBefore, AdviceAfter and AdviceAround marker interfaces are removed. Advice requires getType(): AdviceTypeEnum, with the cases Before, After, AfterThrowing, Around and Introduction.
  • The invocation constructors (DynamicTraitAliasMethodInvocation, StaticTraitAliasMethodInvocation, ReflectionFunctionInvocation) require a non-nullable Closure $closureToCall.
  • DeclareError is removed: the attribute, DeclareErrorInterceptor and PointcutBuilder::declareError(). Emit warnings or throw exceptions from a #[Before] or #[Around] behavior instead.

Methods returning by reference are rejected

Section titled “Methods returning by reference are rejected”

Compiling a method or function declared function &name() fails with a WeavingException, because the call context would return a copy instead of the reference. 3.x returned a copy with a notice. Add && !matchReturningByReference() to rules that match such methods.

? in name and type patterns is no longer a single-character wildcard, because it collided with nullable types. In return-type patterns, a leading ? is a nullable marker: ?Foo equals Foo|null. Replace ? wildcards with *.

The dynamic(...) rule is removed, together with MagicMethodDynamicPointcut, DynamicInvocationMatcherInterceptor, Pointcut::KIND_DYNAMIC and the $instanceOrScope and $arguments parameters of Pointcut::matches(). Intercept the magic method itself and read the invoked name from the arguments.

Before, in 3.x:

3.x
#[Around('dynamic(public Foo->save*(*))')]

After, in 4.0:

4.0
#[Around('execution(public Foo->__call(*))')]
public function aroundMagicCall(MethodInvocation $invocation): mixed
{
[$methodName, $arguments] = $invocation->getArguments();
// ...
return $invocation->proceed();
}
  • Modifier precedence. Space-separated modifiers must all be present, and | binds tighter. final public|protected means final AND (public OR protected). In 3.x it also matched every non-final public method.
  • Foo+ includes Foo. It now also matches the class or interface Foo itself, and classes that use the trait Foo. Add && !within(Foo) to exclude the type itself.
  • Attribute rules match subclasses. @execution(Attr) and the other attribute rules also match attributes extending Attr.
  • * also matches nothing. In name and return-type patterns, * stands for any characters of one name part, including none. In 3.x it needed at least one character: Sensor* skipped the class Sensor itself, and set* skipped a method named set(). Such rules now match them as well. Exclude them with && !execution(public Foo->set(*)) or && !within(Foo) if needed.
  • | alternatives stay inside their name part. Ns\A|B selects Ns\A and Ns\B. In 3.x it meant Ns\A or the global class B. A pattern that listed classes of different namespaces (Foo\A|Bar\B) has to be written as two rules: execution(public Foo\A->*(*)) || execution(public Bar\B->*(*)).
  • ModifierPointcut is final and immutable. The masks are constructor arguments, and andMatch(), orMatch() and notMatch() return a new instance.

The original class body is converted into a trait, <Class>OriginalTrait. The proxy class keeps the original name, parent and interfaces, and uses that trait with private <method>OriginalAlias aliases. In 3.x the proxy extended a renamed <Class>__AopProxied parent class. This affects code that relied on that inheritance layer:

  • The proxy has no renamed parent class any more. get_parent_class(), parent:: inside the class and instanceof checks see the original parent.
  • AspectContainer::AOP_PROXIED_SUFFIX is removed. Use ORIGINAL_TRAIT_SUFFIX ('OriginalTrait') or ORIGINAL_TRAIT_FILE_SUFFIX ('OriginalTrait.php').
  • AbstractMethodInvocation::TRAIT_ALIAS_PREFIX is replaced by TRAIT_ALIAS_SUFFIX ('OriginalAlias').
  • The hooks of InitializationAware and StaticInitializationAware are named __initialization() and __staticInitialization().
  • self:: in generated code resolves to the proxy class, so SelfValueTransformer and SelfValueVisitor are removed.
  • Go\Aop\Features is a final class instead of an interface. The constants are unchanged, but it can no longer be implemented. Features::ALL combines every flag, and AspectKernel::hasFeature() throws on an unknown flag.
  • Features::PARAMETER_WIDENING is removed. Delete the flag from your kernel options if you passed it.

These public classes, methods and constants had no use inside the framework and are removed:

  • The #[Aspect] attribute (Go\Lang\Attribute\Aspect). The framework never read it: behavior classes are identified by implementing Go\Aop\Aspect. Remove the attribute from your behavior classes.
  • Pointcut::KIND_TRAIT. Pointcut::KIND_ALL is 119 instead of 127.
  • Go\Proxy\Part\InterceptedConstructorGenerator and Go\Proxy\Part\FunctionParameterList.
  • InterceptedMethodGenerator::getBody() and setBody(), CachePathManager::setCacheDir(), and AopComposerLoader::wasInitialized(). AopComposerLoader::init() returns the same flag.
  • The 'kernel.options' container entry. Use AspectKernel::getOptions().
3.x / earlier 4.0 development 4.0
TransformerResultEnum::RESULT_TRANSFORMED TransformerResult::Transformed
TransformerResultEnum::RESULT_ABSTAIN TransformerResult::Abstain
TransformerResultEnum::RESULT_ABORTED TransformerResult::Aborted
FieldAccessType::READ / WRITE FieldAccessType::Read / Write
AspectContainer::AOP_PROXIED_SUFFIX AspectContainer::ORIGINAL_TRAIT_SUFFIX
AspectContainer::getValue() AspectContainer::get() (PSR-11)

The Go\Proxy\Generator enums (Visibility, PropertyModifier, ClassModifier) use PascalCase cases as well. Custom source transformers return TransformerResult cases, and behaviors comparing getAccessType() use the new case names:

if ($access->getAccessType() === FieldAccessType::WRITE) {
if ($access->getAccessType() === FieldAccessType::Write) {
  • AspectKernel::registerTransformers(), which returned transformer instances, is replaced by registerTransformerServices(AspectContainer $container), which registers deferred container services. Override it to replace, omit, reorder or extend the built-in transformers. To append one, call $container->addLazyService(MyTransformer::class, ...) from configureAop().
  • CachingTransformer is removed: the cache decision lives in SourceTransformingLoader. SourceTransformingLoader::addTransformer() is removed, and transformCode() returns the overall TransformerResult.
  • StreamMetaData::$source is read-only: it is rebuilt from $tokenStream on every read. Custom transformers edit the tokens in $tokenStream, or replace them with setTokenStreamFromRawTokens().
  • ConstructorExecutionTransformer, FilterInjectorTransformer and MagicConstantTransformer are no longer SourceTransformers. They are NodeRewriter rules, applied by one SyntaxTreeRewriter walk over the syntax tree. That walk is a framework service: it opens the chain before WeavingTransformer, even when registerTransformerServices() is overridden.
  • Custom SourceTransformers are registered as before. To rewrite single nodes, register a NodeRewriter service instead of a transformer that walks the tree itself. See Configuration for extending the transformation pipeline.

Classes that were never meant to be extended are final now:

  • Go\Core\Container, Go\Core\AttributeAspectLoaderExtension
  • Go\Aop\Framework\StaticInitializationJoinpoint
  • Go\Instrument\ClassLoading\AopComposerLoader, SourceTransformingLoader, Go\Instrument\PathResolver
  • the transformers WeavingTransformer, FilterInjectorTransformer, MagicConstantTransformer and StreamMetaData
  • the proxy generators EnumProxyGenerator, TraitProxyGenerator and FunctionProxyGenerator
  • the attributes #[Before], #[After], #[Around], #[AfterThrowing], #[Pointcut] and #[DeclareParents]

Go\Lang\Attribute\AbstractInterceptor is abstract. Classes that are only part of the framework’s machinery are marked @internal and are not covered by BC promises: AdviceMatcher, AspectLoader, CachedAspectLoader, CachePathManager, CacheWarmer, Enumerator, InterceptorInjector, The and NativeLazyProxy.

Replace subclasses of these classes with composition, or with your own container or transformer registered in configureAop() or registerTransformerServices().

Every exception thrown by the framework implements Go\Aop\Exception\ExceptionInterface, so one catch handles any of its failures. Several throw sites changed their type:

Situation 3.x 4.0
Invalid kernel options, container registrations, console input RuntimeException, InvalidArgumentException, UnexpectedValueException InvalidConfigurationException (an InvalidArgumentException)
Invalid matching rule UnexpectedValueException, InvalidArgumentException PointcutSyntaxException (an AspectException)
Unknown container id OutOfBoundsException ServiceNotFoundException (an OutOfBoundsException and a PSR-11 NotFoundExceptionInterface)
Container entry of the wrong type in getService() InvalidArgumentException ContainerException (an InvalidConfigurationException and a PSR-11 ContainerExceptionInterface)
Compilation, proxy generation, cache writes RuntimeException, LogicException, InvalidArgumentException WeavingException (a RuntimeException)
Behavior that cannot be cached Go\Core\Cache\NotCompilableException Go\Aop\Exception\NotCompilableException
Invalid behavior class, call-context runtime errors Go\Aop\AspectException Go\Aop\Exception\AspectException, Go\Aop\Exception\InvocationException

Where you caught the SPL types listed above, catch ExceptionInterface or the new types.

The bridge no longer rewrites entity metadata. The 3.x mapped-superclass workaround only applied to the extend-based engine, and Doctrine maps a compiled entity correctly as it is. Configure two things instead (Doctrine ORM 3.6+):

use Doctrine\ORM\Events;
use Doctrine\ORM\Mapping\Driver\AttributeDriver;
use Go\Bridge\Doctrine\MetadataLoadInterceptor;
use Go\Bridge\Doctrine\WovenEntityClassLocator;
// Discover entities through the autoloader, which serves the generated classes
$configuration->setMetadataDriverImpl(
new AttributeDriver(WovenEntityClassLocator::createFromDirectories([__DIR__ . '/src/Entity'])),
);
// Intercepted properties become hooked properties, which Doctrine supports with native lazy objects
$configuration->enableNativeLazyObjects(true);
// Optional: reports misconfiguration early; a plain listener, no longer an EventSubscriber
$eventManager->addEventListener(Events::loadClassMetadata, new MetadataLoadInterceptor());

The commands declare their names with #[AsCommand] and are loaded lazily by bin/aspect. Every command returns Command::SUCCESS or Command::FAILURE.

  • In 3.x, debug:weaving returned the raw error count. If a script relied on that number, check the exit code instead.
  • cache:warmup:aop fails when a file cannot be compiled, so a deploy script that ignored warmup errors now stops there. Add --fail-fast to stop at the first error:
Terminal window
vendor/bin/aspect cache:warmup:aop public/index.php --fail-fast

© 2026 Alexander Lisachenko