Documentation

No matching pages.

API

Config

Facade

Lifecycle

AOP (Aspect-Oriented Programming)

Apply cross-cutting concerns such as transactions, caching, retries, and logging through PHP 8 attributes.

The model

The implementation has one invocation object, interceptor contract, and chain:

  1. Azera\Aop\Invocation — the single context object passed to every interceptor.
  2. Azera\Aop\InterceptorInterface — intercept(Invocation $invocation, callable $next): mixed.
  3. Azera\Aop\Pipeline — precomposes the chain once, in the constructor.
  4. Azera\Aop\ProxyFactory — reads advice attributes once and generates a subclass. Its overrides create an Invocation and run a precomposed Pipeline.
attributes ──reflection, once──► generated class (one Invocation per call)
                                      │
                                      └─► AopRuntime::plan() memoizes the Pipeline per (class, method)

The transparent layer uses reflection during proxy generation, not during intercepted calls.

Upgrading from ≤ 0.6? See UPGRADING.md — the intercept() signature changed and PipelineHandler was removed. Pipeline::through() is deprecated but still works.

The contract

namespace Azera\Aop;

interface InterceptorInterface
{
    public function intercept(Invocation $invocation, callable $next): mixed;
}

$next runs the next interceptor or, at the innermost frame, the wrapped callable.

Invocation carries everything an interceptor can observe:

Member Type Meaning
target object|string|null the proxied instance; on explicit calls, the callable if it is an object, otherwise null
method ?string the proxied method name, or null for explicit calls
identity string stable label: Class::method, file:line for closures, or a supplied label
args array arguments; reference elements remain references across the chain
parameterNames list<string> proxy-provided parameter names; empty for explicit calls
attributes array<string,mixed> per-call state shared by interceptors
advice(class-string) ?Advice advice configured for this call, or null

A typical interceptor:

final class Timed implements InterceptorInterface
{
    public function intercept(Invocation $invocation, callable $next): mixed
    {
        $start = hrtime(true);

        try {
            return $next($invocation);
        } finally {
            $this->record($invocation->identity, hrtime(true) - $start);
        }
    }
}

Argument references

Reference arguments survive the chain in both entry points:

  • Transparent (proxy): generated overrides retain reference arguments, and the terminal frame calls parent::method(...) through a by-reference variadic closure.
  • Explicit (Pipeline::call): pass references in $args (for example, [&$x]) to preserve them for the callable.

Interceptors may mutate or replace $invocation->args; downstream interceptors and the callable see the changes. Replacing the array preserves references only if they are carried into the new array.

Advice beats constructor defaults

Interceptors can define constructor defaults for calls without attributes. On proxied methods, configured advice values take precedence:

new RetryInterceptor(defaultTimes: 5);   // constructor default, explicit calls use this

#[Retry(times: 2, backoff: 0)]           // attribute wins on the proxied call
public function flaky(): void { ... }

If an interceptor requires advice and has no meaningful default, the sailantis/azera-aop package throws a LogicException naming the missing advice.

Explicit AOP (Pipeline)

use Azera\Aop\Pipeline;
use Azera\Aop\RetryInterceptor;

$pipeline = new Pipeline([new RetryInterceptor(defaultTimes: 3)]);
$result   = $pipeline->call(fn() => $service->chargeCard(100));

// Short form
$result = Pipeline::wrap([new RetryInterceptor(defaultTimes: 3)], fn() => $service->chargeCard(100));

Pipeline::call(callable $callable, array $args = [], ?string $identity = null, array $advice = []): mixed

  • $args is passed to the callable spread as arguments. Reference elements survive.
  • $identity overrides the identity. Without it, closures use file:line (one reflection per call; pass identity: to avoid reflection), while string and array callables use their callable value.
  • $advice passes an advice map ([Transactional::class => new Transactional(...)]) for interceptors that read advice.

Attribute configuration on the explicit path

The explicit path has no method from which to read attributes, so pass advice explicitly:

  • #[Transactional('analytics')] is not read. Pass advice: [Transactional::class => new Transactional('analytics')]; otherwise the interceptor uses its defaultRole (default: write).
  • For #[Cache(key: 'user_{id}')], {id} is resolved from string keys in $args because explicit calls have no parameterNames. Positional arguments cannot provide the name, and unresolved placeholders raise a LogicException. String keys are also spread as PHP named arguments and must match the callable's parameter names (for example, ['id' => 42] for function (int $id)). Without key, the cache key is a digest of $identity, method, and arguments.
  • Advice passed through advice: uses the same interpolation as proxy calls; named arguments are the only parameter-name source on the explicit path.

Transactional, explicitly

Transactions use the same interceptor on the explicit path, including savepoint nesting and failed-COMMIT handling.

use Azera\Aop\Pipeline;
use Azera\Aop\TransactionalInterceptor;

$write   = new Pipeline([new TransactionalInterceptor($ctx->dbManager())]);
$billing = new Pipeline([new TransactionalInterceptor($ctx->dbManager(), defaultRole: 'billing')]);
// Commits on return, rolls back and re-throws on any Throwable.
$order = $write->call(
    fn() => $orderService->createOrder($data),
    identity: 'OrderService::createOrder',   // skip closure reflection, name it in logs
);
// The write connection is the default; name another role through the advice map.
$billing->call(
    fn() => $invoiceService->charge($invoiceId),
    identity: 'InvoiceService::charge',
    advice: [Transactional::class => new Transactional(connection: 'billing')],
);

The explicit path has the same behavior as the proxy:

  • Nested calls use savepoints. An advised call nested on the same connection uses begin(true); an inner failure rolls back to the savepoint, allowing the outer call to commit.
  • A failed COMMIT surfaces its own error. The nesting counter is reconciled with the driver so a secondary "There is no active transaction" error does not mask the cause.

The connection role must come from the interceptor's defaultRole: or a per-call advice: map because explicit calls have no method attributes. An unconfigured role raises an error listing the configured roles; it does not fall back to the default connection.

Passing advice: allocates a Transactional instance per call. For hot paths, configure the role on the pipeline's interceptor instead.

Transparent AOP (proxy generation)

How it works

  1. Mark a class with #[Advised].
  2. Mark methods with advice attributes (#[Transactional], #[Cache], …).
  3. Register the matching interceptors (AppContext::registerInterceptor).
  4. Register the service by class-string so AppContext::build() proxies it.

build() checks in-process memos and the proxy file header. On a miss, it reads advice arguments and generates a subclass that overrides advised methods only. Proxies use one file per class, or eval() when disk caching is disabled.

Each override gets a memoized plan from AopRuntime, creates an Invocation, and calls the pipeline. Advice is constructed from arguments embedded in the proxy; attributes are not reflected at runtime. The terminal calls parent::method(...) through a per-call by-reference variadic closure.

Proxies declare no properties, so instances can be cloned and serialized without colliding with target properties. The namespace derives from the cache directory, keeping interceptor maps separate across factories and stable across processes.

With disk caching (the AppContext default), proxies use the named class AzeraAopProxy_<Class>_<digest>, derived from the target, emitted body, and generator version. The digest is in the class name, not the filename: changed bodies get a new class and replace the file in place. Atomic writes are reusable by OPcache. setAopCacheDir(null) uses anonymous eval() classes without disk caching.

Advice arguments are generated

Generated methods embed advice constructor arguments:

$__plan = \Azera\Aop\AopRuntime::plan(
    namespace: 'factory:/app/temp/aop',
    class: 'App\OrderService',
    method: 'getOrder',
    advice: ['Azera\Aop\Cache' => ['ttl' => 60, 'key' => 'order_{id}']],
    parameterNames: ['id'],
);

Attribute changes alter the generated body and digest; already-loaded classes retain their metadata.

Named and positional forms are preserved. Values must be stable PHP literals: scalars, arrays, enum cases, class constants, or null. Object arguments are rejected because var_export() may require __set_state().

Writes and OPcache

Atomic writes are backdated past opcache.file_update_protection for immediate caching. Each class has one file, replaced only when its body changes. Unchanged bodies keep their mtime so OPcache can reuse the bytecode. Cache directories use mode 0700; group/world- writable directories are rejected.

One file per class, with a metadata header

Each proxied class has a Proxy_<key>.php file, where the key is xxh3(namespace, class). The file begins with a comment header:

<?php
/*azera-aop:{"v":8,"proxy":"AzeraAopProxy_App_OrderService_9a1c…","class":"App\\OrderService","map":"Azera\\Aop\\Cache","sig":"1733238…:8412"}*/
class AzeraAopProxy_App_OrderService_9a1c… extends \App\OrderService

sig records the source file's mtime:size; map lists registered advice classes. They are reuse hints, not keys, and mismatches trigger regeneration. The header can be read without loading the class, allowing stale proxies to be replaced before requiring their parent class.

The stable path avoids duplicate files: unchanged proxies are not rewritten, and changed ones replace the existing file. Since the class name hashes the emitted body, changed bodies use a new class rather than redeclaring one.

Writes are one file per class; timestamps are only a hint

Workers with stale metadata keep their loaded class name; fresh processes derive a new one, and the first process to notice replaces the file. Classes without a usable source signature (traits, internal, or eval'd classes) always regenerate.

What a deploy must do

Source changes are visible only to processes that have not memoized the previous version:

Memo Scope Cleared by
ProxyFactory::$proxyClassCache factory register(), setCacheDir(); context registration replaces the factory
ProxyFactory::$loadedProxies process process restart
AopRuntime::$plans process clearPlans() (registerInterceptor() calls it)
Loaded bytecode OPcache opcache_reset() / reload when timestamp validation is disabled

The first two checks precede reflection. In the measured setup, they take about 3 µs, compared with about 140 µs for scanning, generation, and hashing.

Attribute edits generate a new proxy and plan, but existing services retain their plan; replace workers after advice changes. Method-body edits take effect on the next load through parent::method(...):

systemctl reload php8.5-fpm     # keeps workers: still holding the old instances
systemctl restart php8.5-fpm    # new workers construct from the new proxy files
php -r 'opcache_reset();'       # or drop opcache.validate_timestamps=0 reloads

Reclaiming space

Normal use does not leave obsolete proxy files because each class has one file that is replaced in place. Use cache:clear --only=aop to recover from an untrusted cache:

php azera cache:status             # file count, size, and any files from an earlier release
php azera cache:clear --only=aop   # wipe the directory; proxies regenerate on demand

Clear the cache after upgrading from before 0.7. Those versions named proxy files after the emitted body (Proxy_<digest>.php), leaving obsolete files at old paths. This generator cannot read or replace them; status reports their count. Clearing also removes manifests and temporary files from interrupted writes. Current proxies are rebuilt on first use, at the same cost as a cold start.

By default, proxies are stored in the host-wide <temp>/azera_aop directory. Applications with different proxied classes can share it because files are keyed by namespace and class. Deployments of the same code with different advice for a class share a file path and replace its contents when rebuilding. This remains correct because the class name includes the emitted-body digest and the header is revalidated. Use setAopCacheDir() to isolate deployments.

Enabling AOP

use Azera\Aop\Transactional;
use Azera\Aop\TransactionalInterceptor;

$ctx->setAopCacheDir(dirname(__DIR__) . '/temp/aop');   // null = eval() for development
$ctx->registerInterceptor(Transactional::class, new TransactionalInterceptor($ctx->dbManager()));

Register interceptors before resolving advised services. Late registration is tolerated — already-resolved #[Advised] instances are evicted and rebuilt on the next resolve, keeping the registered recipe (class string or factory) so the service comes back the way the application wired it — but nothing already executing can be retrofitted.

Using AOP

use Azera\Aop\Advised;
use Azera\Aop\Transactional;
use Azera\Aop\Cache;

#[Advised]
class OrderService
{
    #[Transactional]
    public function createOrder(array $data): Order
    {
        // begin() before, commit() after, rollback() on throwable
    }

    #[Cache(ttl: 60, key: 'order_{id}')]
    public function getOrder(int $id): ?Order
    {
        return Order::find($id);
    }
}

Critical: autowiring vs factory

The service must be registered as a class string for the proxy to be generated. build() is only reached for class-string definitions:

// Correct: build() generates the proxy
$ctx->set(OrderService::class);

// Wrong: factory returns a plain instance, no proxy
$ctx->set(OrderService::class, fn() => new OrderService(...));

Constructor dependencies are resolved automatically during autowiring.

Built-in advice

Attribute Interceptor Notes
#[Transactional] TransactionalInterceptor savepoints for nesting; connection: selects a role
#[Cache(ttl, key?)] CacheInterceptor {argName} placeholders; derived key is one xxh128 digest of the triple
#[Retry(times, backoff)] RetryInterceptor times is the total attempt count
#[Log(level, logArgs)] LogInterceptor logs entry, exit, duration, exception

Prefixes, package sailantis/azera-aop:

Attribute Interceptor
#[Audit] AuditInterceptor
#[Authorize] AuthorizeInterceptor
#[Bulkhead] BulkheadInterceptor
#[CircuitBreaker] CircuitBreakerInterceptor
#[Idempotent] IdempotentInterceptor
#[Throttle] ThrottleInterceptor
#[Trace] TraceInterceptor
#[Validate] ValidateInterceptor

#[Transactional]

Wraps the method in a database transaction: begin() before, commit() after, rollback() on any Throwable (then the exception is re-thrown). Nested #[Transactional] calls use savepoints.

#[Transactional]
public function transfer(int $from, int $to, float $amount): void { ... }

#[Transactional(connection: 'analytics')]
public function recordEvent(Event $e): void { ... }

A failed COMMIT surfaces its original error. The interceptor avoids a redundant rollback that could mask it and reconciles the connection's nesting counter with the driver.

The advice must use the same connection role as the write path. If a model redirects writes (Model::setDefaultWriteRole() or #[Connection]), a mismatched role leaves those writes outside the transaction. Set detectLeakedConnections: true to detect connections left open on other roles. Detection runs before COMMIT and rolls back the unit of work, so a retry cannot replay already-committed writes. Connections already in a transaction before the advised method are not reported.

An explicitly named role must be configured or the interceptor throws. An unnamed role uses the interceptor's defaultRole (default: write) and falls back to the manager's default connection when that role is not configured.

#[Cache]

Caches the return value under a key derived from (identity, method, args), or under a literal template when key: is given.

#[Cache(ttl: 300)]                          // derived key
public function getProfile(int $userId): Profile { ... }

#[Cache(ttl: 600, key: 'user_{userId}_profile')]   // literal key
public function loadProfile(int $userId): Profile { ... }

The derived key is one 32-character xxh128 digest of serialize([$identity, $method, $args]). It is opaque and avoids identity sanitization, length limits, and per-call memoization; it is also roughly one-third cheaper than the former readable format.

Serialization preserves distinctions between inputs, including ('ab', 'c') and ('a', 'bc'), null and '' method names, string and numeric argument keys, and 1, '1', and 1.0.

Placeholders in an explicit key: template resolve against argument values. Resolved values are not scanned again, and unresolved placeholders raise a LogicException.

Every value gets a distinct, type-prefixed, key-safe token, so different arguments cannot collapse onto one entry:

Argument Token
null, true, false null, true, false
int the integer
short, key-safe string s_<value> (s_user_42)
float f_<value>
any other string / array / object str_ / arr_ / obj_ + a digest
unserializable value (closure, resource) throws

Type prefixes keep distinct values separate: 42, '42', and 42.0 produce different keys, as do 'null' and null. Unreferenced arguments are not tokenized, so an unserializable value does not prevent resolving a key that does not use it.

Note:

  • xxh128 is not resistant to adversarial collisions. For attacker-controlled arguments where a collision could expose cached data, use an explicit key: template.
  • Changing the key format invalidates existing entries; treat it as a cache version change.

Not everything can be advised

Proxy advice overrides methods, so:

  • a final method carrying an advice attribute cannot be overridden — remove final, or wrap it;
  • a final class cannot be extended at all — advice on its methods is unresolvable.

Both conditions raise a RuntimeException naming the class and method when the proxy is built.

Writing a custom interceptor

use Azera\Aop\Advice;
use Attribute;

#[Attribute(Attribute::TARGET_METHOD)]
class Audited extends Advice
{
    public function __construct(public readonly string $action) {}
}

final class AuditInterceptor implements InterceptorInterface
{
    public function __construct(private AuditLog $log) {}

    public function intercept(Invocation $invocation, callable $next): mixed
    {
        $advice = $invocation->advice(Audited::class);   // null in explicit mode unless passed via advice:

        $result = $next($invocation);

        $this->log->record($advice?->action ?? 'unknown', [
            'target' => $invocation->identity,
            'args'   => $invocation->args,
        ]);

        return $result;
    }
}

Register it like any built-in:

$ctx->registerInterceptor(Audited::class, new AuditInterceptor($auditLog));

#[Advised]
class OrderService
{
    #[Audited(action: 'order.cancelled')]
    public function cancel(int $id): void { ... }
}

Invocation::$attributes is the scratch space for inter-interceptor state (timers, attempt counters). Keep it per-call — never stash it on the interceptor instance, which is shared across calls and requests in the same process.

Performance

Measured with hrtime over five runs of 100k calls each (see benchmarks/aop-overhead.php), using PHP 8.3.31 (ZTS, xdebug off) on one Windows 11 machine. These figures are indicative, not portable guarantees; allocators, OPcache, and CPU frequency can shift results. Reproduce with:

php -d xdebug.mode=off benchmarks/aop-overhead.php

A representative run:

Scenario ns/call
Raw method call ~69
Pipeline, 0 interceptors (closure hoisted at the call site) ~222
Pipeline, 0 interceptors (closure built per call, as in the loop) ~228
Pipeline, 1 (Retry), default identity ~1064
Pipeline, 1 (Retry), identity: passed ~1146
Pipeline, 2 (Retry + Log), default identity ~1984
Pipeline, 2 (Retry + Log), identity: passed ~1997
Pipeline, 3 (Retry + Log + Cache, warm) ~2820
Proxy, 1 (Retry) ~1352
Proxy, 2 (Retry + Log) ~2140
Proxy, 3 (Retry + Log + Cache, warm) ~3056

A zero-interceptor pipeline is a plain variadic call, with no Invocation, identity derivation, or chain frame. With a long-lived callable, $pipeline->call($fn, [7]) took ~181 ns (~113 ns over a raw call); with a new closure per iteration, it took ~229 ns. Most of the difference comes from allocating the closure at the call site.

Observations from five consecutive full runs on this machine:

  • Passing identity: saved a median of ~80 ns by skipping closure reflection (range: −12 to +137 ns across runs).
  • With one interceptor, the proxy was 180–250 ns slower in all five runs, partly due to its per-call terminal closure, extra method frame, and Invocation construction.
  • With two interceptors, proxy and explicit calls were within noise (−137 to +160 ns).
  • With three interceptors and a warm cache, the proxy was 67–562 ns faster in four of five runs. Both paths short-circuit in CacheInterceptor, so this measures dispatch and cache-hit cost, not a general proxy advantage.
  • The proxy's reduced identity derivation, advice lookup, and interceptor resolution can benefit longer chains. At one interceptor, these gains are offset by proxy overhead.

Do not optimize against these figures. Interceptor work, such as a database round trip, typically costs microseconds to milliseconds; dispatch is negligible by comparison.

Registration-state costs:

State Cost
No interceptors registered zero — build() returns a plain instance
Interceptors registered, class not #[Advised] one memoised lookup after the first construction — the parent-chain check runs once per class, not once per instance
#[Advised] but no advised methods one attribute scan, then a plain instance
#[Advised] with advised methods generation once per (class, method) shape; thereafter an OPcache'd file or eval'd class

Non-advised methods on a proxied class are not overridden and add no proxy dispatch cost.