Skip to content
Documentation

Behaviors & Matching Rules

The complete reference for writing behaviors, the dynamic middleware the framework runs around your code, and the matching rules that say where they apply.

This page covers everything you write when you work with the framework: behavior classes, the behaviors in them that run as dynamic middleware around your code, the call context each behavior receives, and the matching rules that select where it runs. If you have not set up a kernel yet, start with Getting Started. For complete walkthroughs from problem to working code, see the caching behavior and the logging behavior.

The framework’s API keeps the classic names, so you will meet them in code, in class names and in error messages. These docs use the everyday words and name the API term once:

In these docs In the API What it is
Behavior class Aspect A class that implements Go\Aop\Aspect and groups related behaviors
Behavior (middleware) Advice A public method of the behavior class with one attribute from Go\Lang\Attribute: #[Before], #[After], #[AfterThrowing] or #[Around]
Matching rule Pointcut The expression in that attribute that selects where the behavior runs
Call context Joinpoint The intercepted moment (a method call, a property access, object creation), passed to the behavior as an object
Compile step Weaving Turning your classes into the files PHP loads, with the behaviors attached
Class extension Introduction An interface and a trait added to existing classes
src/Aspect/ServiceAspect.php
namespace App\Aspect;
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\AfterThrowing;
use Go\Lang\Attribute\Around;
use Psr\Log\LoggerInterface;
class ServiceAspect 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->debug($invocation . ' took ' . (hrtime(true) - $start) . ' ns');
}
}
#[AfterThrowing('execution(public App\Service\*->*(*))')]
public function logFailure(MethodInvocation $invocation, \Throwable $exception): void
{
$this->logger->error($invocation . ' failed: ' . $exception->getMessage());
}
}

A behavior class is a plain PHP class that implements Go\Aop\Aspect. It holds logic such as logging, caching, security checks or transactions that would otherwise be copied into many classes. Each of its behaviors runs as middleware around the code its matching rule selects: measure() above wraps every public method of App\Service, and logFailure() runs when one of them throws. Because it is an ordinary class, you can use constructor injection, private state, traits and everything else PHP offers.

The attribute on a behavior says when it runs relative to the intercepted call.

Attribute Runs
#[Before] Before the call. It can change the arguments with setArguments().
#[After] After the call, also when it throws (like finally).
#[AfterThrowing] When the call throws. It receives the exception as the second argument; the exception is rethrown afterwards.
#[Around] Instead of the call, as middleware does. It decides whether to call proceed(), and its return value becomes the result.

All four attributes live in the Go\Lang\Attribute namespace and take a matching rule as their argument.

src/Aspect/MonitorAspect.php
namespace Aspect;
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Before;
class MonitorAspect implements Aspect
{
#[Before('execution(public Example->*(*))')]
public function beforeMethodExecution(MethodInvocation $invocation): void
{
echo 'Calling Before Interceptor for: ',
$invocation,
' with arguments: ',
json_encode($invocation->getArguments()),
"<br>\n";
}
}

A Before behavior runs right before the original method. Use it to validate input or check permissions. To change what the original method receives, replace the arguments:

#[Before('execution(public App\Service\UserService->rename(*))')]
public function trimName(MethodInvocation $invocation): void
{
$arguments = $invocation->getArguments();
$arguments[0] = trim($arguments[0]);
$invocation->setArguments($arguments);
}

getArguments() lists the arguments by position, so you address them by index.

use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\After;
#[After('execution(public App\Service\ImportService->run(*))')]
public function releaseLock(MethodInvocation $invocation): void
{
$this->lock->release();
}

An After behavior works like a finally block: it runs whether the method returns normally or throws. Use it to release resources or stop timers.

use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\AfterThrowing;
#[AfterThrowing('execution(public App\Service\*->*(*))')]
public function logFailure(MethodInvocation $invocation, \Throwable $exception): void
{
$this->logger->error($invocation . ' failed: ' . $exception->getMessage());
}

An AfterThrowing behavior runs only when the call throws. It receives the exception as its second argument. The framework rethrows the exception after the behavior, so the caller still sees it. Use it to log errors or send alerts.

use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Around;
#[Around('execution(public App\Service\*->*(*))')]
public function measure(MethodInvocation $invocation): mixed
{
$start = hrtime(true);
try {
return $invocation->proceed();
} finally {
$this->logger->debug($invocation . ' took ' . (hrtime(true) - $start) . ' ns');
}
}

An Around behavior runs instead of the call, like a middleware in an HTTP stack. You call proceed() to pass control on to the original code, and whatever the behavior returns becomes the result. This makes Around the most capable type: it decides whether the original runs at all, can change the arguments before proceed(), can change the return value, and can catch exceptions. Use it for caching, transactions and retry logic.

If you do not call proceed(), the original method does not run:

#[Around('execution(public App\Service\ReportService->build(*))')]
public function cacheReport(MethodInvocation $invocation): mixed
{
$key = $invocation . json_encode($invocation->getArguments());
return $this->reports[$key] ??= $invocation->proceed();
}

Every behavior receives an object that describes the intercepted call: its arguments, the object it runs on, and proceed() to continue. Its class depends on what the matching rule selects.

Class Received for Main methods
MethodInvocation execution() of dynamic and static methods getThis(), getScope(), getMethod(), getArguments(), setArguments(), proceed()
FunctionInvocation execution() of namespaced functions getFunction(), getArguments(), setArguments(), proceed()
FieldAccess access() of properties getThis(), getField(), getAccessType(), getValue(), getValueToSet(), proceed()
ConstructorInvocation initialization() getConstructor(), getArguments(), getThis() (null before the object exists), proceed()

All of them live in Go\Aop\Intercept. A MethodInvocation can be used as a string, as the examples above do in log messages.

These classes declare @template types, so PHPStan and IDEs know the types of getThis() and proceed(). Write the concrete types in the docblock of your behavior:

use App\Model\Order;
use App\Service\OrderService;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Around;
/**
* @param MethodInvocation<OrderService, Order> $invocation
*/
#[Around('execution(public App\Service\OrderService->place(*))')]
public function auditOrder(MethodInvocation $invocation): Order
{
$order = $invocation->proceed();
// …
return $order;
}

Here MethodInvocation<OrderService, Order> tells the analyser that getThis() is an OrderService and proceed() returns an Order.

There is no magic behind attaching a behavior. For every intercepted method the framework generates a plain middleware chain. Each behavior is referenced as a closure created with first-class callable syntax, right on the behavior class instance:

static $__joinPoint = InterceptorInjector::forMethod(
self::class,
'doSomething',
[
Interceptor::before(The::aspect(MonitorAspect::class)->beforeMethodExecution(...)),
],
$this->doSomethingOriginalAlias(...),
);

The::aspect() fetches the behavior class instance from the kernel’s container, and ->beforeMethodExecution(...) is the behavior method you wrote. You can Ctrl-click it in your IDE, set a breakpoint inside it and step through the generated code as if it were handwritten. The call contexts are built at compile time and cached in the generated code, so there is no runtime reflection or attribute parsing. See Debuggable for more on the generated code.

Behaviors registered in the container as plain closures, rather than methods of a behavior class, are attached through the lazy The::advice() accessor instead. It looks up the registered entry by its identifier and unwraps it down to the raw closure:

Interceptor::around(The::advice('advisor.Demo\Aspect\DynamicMethodsAspect->aroundMagicMethods')),

A matching rule is an expression that selects where a behavior runs: method executions, property accesses, function calls or object creation. It is the argument of the behavior’s attribute:

#[Before('execution(public App\Service->save(*))')]

The playground lets you try rules on a PHP file; this section is the full reference.

Rule Selects
execution(modifiers Class->method(*)) Execution of a dynamic method
execution(modifiers Class::method(*)) Execution of a static method
execution(Namespace\function(*)) Calls of a system function from that namespace
access(modifiers Class->property) Reads and writes of an instance property
within(ClassFilter) Every member (methods and properties) of the matching classes
initialization(ClassFilter) Object creation with new
staticinitialization(ClassFilter) The first load of the matching classes
@execution(Attribute) Methods that carry the attribute
@access(Attribute) Properties that carry the attribute
@within(Attribute) Every member of classes that carry the attribute
matchInherited() Only members inherited from a parent class or imported from a trait; !matchInherited() excludes them
matchReturningByReference() Methods and functions declared function &name(); !matchReturningByReference() excludes them
$this->pointcutName A named rule declared with #[Pointcut] on a method of the same behavior class
Aspect\Class->pointcutName A named rule of another behavior class

The argument list is always (*): arguments are not matched.

Note the separator: -> selects dynamic methods, :: selects static ones.

execution(public App\Service\OrderService->place(*))
execution(public App\Util\Money::format(*))

To intercept calls of magic methods, attach the behavior to __call itself:

execution(public Foo->__call(*))
Pattern Meaning
* Any characters of one name part, including none, never crossing a \: get* (also get), *Service (also Service), App\*\Controller (exactly one namespace level between)
** Any namespace depth: App\** is every class below App, **->*(*) is every method
a|b Alternatives within one name part, e.g. get*|is*. They apply to the part they are written in: App\Cart|Order is App\Cart or App\Order, never a global Order. For classes of different namespaces join two rules with ||
Foo+ Foo itself, its subclasses and implementers, and classes that use the trait Foo (directly or through a parent class)

Names are matched case-sensitively. Write namespaces with a single backslash; in a PHP string with single quotes no escaping is needed.

execution(public **->save*(*))
execution(public App\Repository\*Repository->find*|get*(*))
execution(public App\Contract\Cacheable+->*(*))

Method and property rules accept these modifiers:

  • public, protected, private
  • final, readonly
  • the asymmetric visibility modifiers private(set) and protected(set)

Combine alternatives with |:

execution(public|protected App\Service->*(*))

Modifiers separated by spaces must all be present, and | binds tighter than the space. final public|protected matches final methods that are public or protected. One group of alternatives is supported per pattern.

Static properties are never intercepted, and neither are readonly properties or properties that already have hooks. The property interception section below lists every case; the reasons are on Limitations & Upgrading.

A method or function pattern can restrict the declared return type:

execution(public App\Repo->find*(*): App\Entity|null)

Union types use |, intersection types &, and ?Foo is the same as Foo|null.

Operator Meaning
&& Both match
|| Either matches
! Negation
( ) Grouping
within(App\**) && !execution(public **->__construct(*))

Comments start with // and run to the end of the line. They help in long multi-line expressions:

#[Around('
execution(public App\Service\**->*(*)) // every public service method
&& !matchReturningByReference() // skip function &name()
&& !matchInherited() // skip inherited and trait methods
')]
public function trace(MethodInvocation $invocation): mixed
{
return $invocation->proceed();
}

Declare a rule once and reference it from several behaviors:

src/Aspect/HealthyLiveAspect.php
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\After;
use Go\Lang\Attribute\Before;
use Go\Lang\Attribute\Pointcut;
class HealthyLiveAspect implements Aspect
{
#[Pointcut('execution(public App\Human->eat(*))')]
protected function humanEat(): void {}
#[Before('$this->humanEat')]
public function washUpBeforeEat(MethodInvocation $invocation): void { /* ... */ }
#[After('$this->humanEat')]
public function cleanTeethAfterEat(MethodInvocation $invocation): void { /* ... */ }
}

The #[Pointcut] method has an empty body; only its attribute matters. Reference it as $this->humanEat from the same behavior class. From another one, use the name of the declaring class, for example App\Aspect\HealthyLiveAspect->humanEat.

@execution, @access and @within select members by the PHP attributes they carry. This lets you mark the code that should get a behavior, instead of matching it by name:

src/Attribute/Cacheable.php
namespace App\Attribute;
#[\Attribute(\Attribute::TARGET_METHOD)]
final class Cacheable {}
src/Aspect/CachingAspect.php
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Around;
class CachingAspect implements Aspect
{
#[Around('@execution(App\Attribute\Cacheable)')]
public function cache(MethodInvocation $invocation): mixed
{
// …
return $invocation->proceed();
}
}

@access(Attribute) does the same for properties, and @within(Attribute) selects every member of classes that carry the attribute. Attributes of compiled classes are copied to the generated code with their original arguments, so reading them at runtime works as before. The caching behavior builds a complete #[Cacheable(ttl: 600)] on this rule.

use Go\Aop\Intercept\FieldAccess;
use Go\Aop\Intercept\FieldAccessType;
use Go\Lang\Attribute\Around;
#[Around('access(public App\Entity\User->email)')]
public function normalizeEmail(FieldAccess $access): mixed
{
if ($access->getAccessType() === FieldAccessType::Write) {
return strtolower($access->proceed());
}
return $access->proceed();
}

access(...) rules intercept reads and writes of instance properties through native PHP 8.4 property hooks on the generated proxy classes. The behavior receives a FieldAccess. For a write, proceed() returns the value that is stored, so an Around behavior can change it, as the example does.

What can be intercepted:

  • properties declared in the compiled class itself, including constructor-promoted properties (also final ones, on PHP 8.5). The assignment made by the constructor is intercepted as a write.
  • inherited public and protected properties from parent classes

What is skipped:

  • static, readonly and already-hooked properties
  • inherited final properties from parent classes
  • inherited private properties

For array-typed properties, the proxy emits only a by-reference &get hook, without set. This keeps indirect modifications such as array_push($this->items, ...) valid.

When Doctrine hydrates or flushes an entity, it reads and writes the raw property values, so property behaviors run only for accesses made by your own code. See Integrations for the Doctrine setup, and the Property hooks feature page for an overview.

src/Aspect/SerializableAspect.php
use App\Model\JsonSerializableTrait;
use Go\Aop\Aspect;
use Go\Lang\Attribute\DeclareParents;
class SerializableAspect implements Aspect
{
#[DeclareParents('within(App\Model\*)', interfaceName: \JsonSerializable::class, traitName: JsonSerializableTrait::class)]
protected null $jsonSerializable;
}
src/Model/JsonSerializableTrait.php
namespace App\Model;
trait JsonSerializableTrait
{
public function jsonSerialize(): mixed
{
return get_object_vars($this);
}
}

A class extension changes what capabilities existing classes expose, where a behavior changes what happens when their code runs. #[DeclareParents] on a property of the behavior class adds an interface and a trait implementing it to the matching classes. Here every class in App\Model becomes JsonSerializable without editing any of them. This works for classes of Composer packages too, see the Class extensions feature page.

use Go\Aop\Intercept\FunctionInvocation;
use Go\Lang\Attribute\Around;
#[Around('execution(App\Service\file_get_contents(*))')]
public function logRead(FunctionInvocation $invocation): mixed
{
$this->logger->debug('Reading ' . $invocation->getArguments()[0]);
return $invocation->proceed();
}

execution(App\Service\file_get_contents(*)) intercepts calls of file_get_contents() from code in the App\Service namespace. The behavior receives a FunctionInvocation.

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.

use Go\Aop\Intercept\ConstructorInvocation;
use Go\Lang\Attribute\Around;
#[Around('initialization(App\Model\Order)')]
public function trackOrderCreation(ConstructorInvocation $invocation): mixed
{
$order = $invocation->proceed();
// …
return $order;
}

initialization(App\Model\Order) intercepts new Order(...) in compiled files. The behavior receives a ConstructorInvocation. Its getThis() returns null before the object exists.

staticinitialization(App\Model\*) runs once, after the class is loaded.

Behavior classes are services of the kernel’s container. Register them in configureAop() of your kernel, preferably as deferred services:

app/ApplicationAspectKernel.php
use Aspect\MonitorAspect;
use Go\Core\AspectContainer;
use Go\Core\AspectKernel;
class ApplicationAspectKernel extends AspectKernel
{
protected function configureAop(AspectContainer $container): void
{
// Deferred (recommended): constructed on first use
$container->addLazyService(MonitorAspect::class, static fn() => new MonitorAspect());
// Eager alternative:
// $container->add(MonitorAspect::class, new MonitorAspect());
}
}

addLazyService() registers a factory. The compile step never instantiates behavior classes: each one is created when one of its behaviors first runs, as a PHP 8.4 native lazy object. add() registers an instance you have already built.

The factory receives the kernel’s container, an AspectContainer. It is a PSR-11 container, so you can pull the dependencies of the behavior class from it:

use Go\Core\AspectContainer;
use Psr\Log\LoggerInterface;
$container->addLazyService(
ServiceAspect::class,
static fn(AspectContainer $c) => new ServiceAspect($c->getService(LoggerInterface::class)),
);

Services of your application’s own PSR-11 container become available once you attach it to the kernel’s container with setDelegate(). Framework bridges for Symfony, Laravel and Yii3 register behavior classes for you; see Integrations. Kernel options are covered in Configuration.

A behavior runs once per method execution, however many classes of the hierarchy are compiled. A method that a compiled class only inherits is intercepted by the nearest compiled ancestor the rule matches there (up to the class declaring the method); the subclass inherits that intercepted method and overrides nothing.

When no such ancestor exists, as for a parent class outside of includePaths or one the rule does not match, the subclass intercepts the inherited method itself.

To restrict a rule to members a class declares itself, add !matchInherited(). It excludes members inherited from a parent class and members imported from a trait.

A few kinds of methods can not get a behavior, or work differently when they do. The full list, with the reasons, is on Limitations & Upgrading. In short:

  • Returning by reference. A method or function declared function &name() can not be intercepted; compiling it fails with a WeavingException. Exclude such methods from a broad rule with && !matchReturningByReference().
  • Trait methods with #[\Override]. A method a class imports from a trait and that carries #[\Override] can not be intercepted in that class; compiling it fails with a WeavingException. Exclude it with && !matchInherited(), or attach the behavior to the trait itself, for example execution(public HelloTrait->hello(*)), which applies in every class using the trait.
  • Generators. 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.
  • Arguments. getArguments() lists the arguments by position. A by-reference variadic parameter (&...$values) is passed to the original method by value.
  • #[\SensitiveParameter]. Two internal frames between the call context and the original method still hold the argument array in Throwable::getTrace(). With zend.exception_ignore_args=On, the production default, no frame has arguments.
  • Properties. Static, readonly and already-hooked properties are not intercepted, nor are inherited final or inherited private properties.

© 2026 Alexander Lisachenko