Teaches coding agents aspect-oriented programming with the Go! AOP framework: writing aspects, pointcuts and advices, framework bridges, deployment, performance, troubleshooting, and refactoring existing object-oriented code into aspects.

GitHub stars
1.7K

Install

/plugin install goaop@goaop

Run it inside Claude Code after adding the marketplace with /plugin marketplace add goaop/framework.

Contents

Discovered from source

Skills 2

Aspect-oriented development with Go! AOP

Go! AOP weaves aspects into PHP classes while they are loaded. It needs no PHP extension and never calls eval(): the woven code is plain PHP in a cache directory.

Version. This skill describes the attribute-based API (Go\Lang\Attribute\*, addLazyService()), which starts with 4.0. The required PHP version is in the composer.json of the package. Older projects (3.x: registerAspect(), protected advices, dynamic() pointcuts) use another API: do not apply this skill to them, and follow UPGRADE-4.0.md of the package when the user wants to migrate.

Documentation of the framework. The skill is self-contained, and the documentation of the framework goes deeper. Where a reference file names docs/<file>.md, find it here:

  • in a project that has the framework installed: vendor/goaop/framework/docs/. It matches the installed version, so it wins when it disagrees with this skill;
  • when this skill is read from a checkout of the framework: docs/ in the root of that repository;
  • otherwise: https://github.com/goaop/framework/tree/master/docs.

Vocabulary

TermMeaning in Go! AOP
AspectA class that implements Go\Aop\Aspect and holds advices. One aspect per concern.
JoinpointA point the framework can intercept: a method execution, a property read or write, a function call, object creation, the first load of a class.
PointcutA string expression that selects joinpoints, e.g. execution(public App\Service\*->save*(*)).
AdviceA public method of an aspect with #[Before], #[After], #[AfterThrowing] or #[Around]. It receives the joinpoint. The woven code refers to it as a first-class callable on the aspect, The::aspect(LoggingAspect::class)->logCall(...), so at runtime an advice is a Closure of that method.
WeavingRewriting a class so that the selected joinpoints call the advices.
Introduction#[DeclareParents]: adds an interface and a trait that implements it to the matching classes.

How weaving works, and what follows from it

When Composer loads a class below the include paths, the framework moves the class body into a trait <Class>OriginalTrait and generates a class with the original name that uses the trait. Every advised method is re-declared there and calls the interceptor chain, then the original body through a private alias. The class keeps its name, parent and interfaces; no object is wrapped.

Four consequences decide most questions:

  1. Advice applies to every call. $this->helper(), private, static and final methods and methods of final classes are intercepted too, because the method itself is replaced. There is no "self-invocation" problem as with proxy objects in other AOP tools.
  2. Only code that is woven can be intercepted. That means classes loaded by Composer after the aspect kernel was initialized, from files below appDir and inside includePaths. A class loaded earlier, an internal PHP class or a class outside these paths is never changed, and nothing reports it.
  3. Matching happens at weave time, on declarations. A pointcut sees class names, method names, modifiers, attributes and declared return types. It does not see argument values or the runtime type of an object. Decide on runtime values inside the advice.
  4. Weaving is cached. In production mode (debug off) the woven classes are served from the cache: an edited source file, aspect or pointcut has no effect until the cache is rebuilt. This is the most common reason for "my change does nothing". Develop in debug mode.

Is an aspect the right tool?

An aspect fits a concern that is the same in many places and independent of the business logic around it: logging, metrics, caching, transactions, retries, circuit breakers, rate limits, authorization checks, audit trails.

Prefer plain code when the behaviour belongs to one or two methods, when the callers must be able to see it, or when it is business logic. An aspect acts at a distance: someone reading OrderService::place() does not see it. Three habits keep that manageable:

  • Select joinpoints with a marker attribute (#[Transactional], #[Cacheable(ttl: 60)]) and an @execution(...) pointcut where possible. The method then shows that something applies to it, and the attribute carries the per-method settings.
  • Keep name-pattern pointcuts as narrow as the concern, and tell the user which methods a new pointcut matches.
  • Keep the contract of the advised method: an advice adds behaviour around the call or fails with an exception. It does not make a method return something its signature does not promise.

Workflow

Step 0: how is Go! AOP integrated into this application?

Look at composer.json before anything else. Most applications run on a framework, and for those the integration is a ready-made package that initializes the kernel at the right moment, takes aspects from the service container, adds console commands and builds the cache with the usual deployment commands. Doing this by hand repeats problems the bridges already solved.

ApplicationUseThen read
Symfonygoaop/goaop-symfony-bundlereferences/frameworks.md
Laravelgoaop/goaop-laravel-bridgereferences/frameworks.md
Yii3goaop/goaop-yii3-bridgereferences/frameworks.md
Another frameworkPropose a reusable bridge first, see "A framework without a bridge" in references/frameworks.mdreferences/frameworks.md, references/setup.md
Plain PHP, a legacy application, a libraryAn AspectKernel of your ownreferences/setup.md

If the bridge of the framework is not installed yet, install it instead of writing a kernel.

Adding an aspect

  1. Write the pointcut. Read references/pointcuts.md when you need more than a simple execution(...): wildcards, | and + have rules that are easy to get wrong.

  2. Write the aspect: a class implementing Go\Aop\Aspect, one public method per advice. references/advices.md has the joinpoint API and the execution order; references/recipes.md has complete, tested aspects for the usual concerns.

  3. Register it. With a bridge, the way the bridge discovers aspects (references/frameworks.md); otherwise in configureAop() of the kernel. An aspect that is not registered is silently ignored.

  4. Verify that it matches. Do not assume: a pointcut that matches nothing is not an error. The debug:advisor command lists every member an advisor matches; the advisor id is <aspect class>-><advice method>.

    IntegrationCommand
    Symfonybin/console debug:advisor --advisor='App\Aspect\LoggingAspect->log'
    Laravelno such command: read the woven class, see below
    Yii3./yii aop:debug:advisor --advisor='App\Aspect\LoggingAspect->log'
    Own kernelvendor/bin/aspect debug:advisor public/index.php --advisor='App\Aspect\LoggingAspect->log'

    Inside a framework the command runs on the kernel the application initialized. Only vendor/bin/aspect takes the file that initializes the kernel as its first argument, and it needs symfony/console. Where no such command is available, run the code once in debug mode and read the woven class: references/troubleshooting.md, "Looking at the woven code".

  5. Run the code and check the behaviour. In production mode, rebuild the cache first.

Minimal example

<?php

declare(strict_types=1);

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\**->*(*)) && !execution(public **->__construct(*))')]
    public function measure(MethodInvocation $invocation): mixed
    {
        $start = hrtime(true);
        try {
            return $invocation->proceed();
        } finally {
            $this->logger->debug('{method} took {ms} ms', [
                'method' => (string) $invocation,
                'ms'     => (hrtime(true) - $start) / 1e6,
            ]);
        }
    }
}

With a bridge the aspect is an ordinary service of the application: the container injects the logger. With a kernel of your own it is registered in configureAop():

$container->addLazyService(
    TimingAspect::class,
    static fn(AspectContainer $c): TimingAspect => new TimingAspect($c->getService(LoggerInterface::class)),
);

Rules that are easy to get wrong

These come from the framework, each with its reason. Breaking one either throws while weaving or, worse, does nothing.

  • Advice methods are public. The generated code calls them as first-class callables on the aspect instance. A protected or private advice throws AspectException. Methods that only carry #[Pointcut] may have any visibility.
  • One advice attribute per method. Two of them throw AspectException. Write two methods that share a named pointcut.
  • The argument list of a pointcut is always (*). Arguments are not matched; ->save() and ->save(int) are syntax errors.
  • * stays inside one namespace level, ** crosses levels. App\*->*(*) matches classes directly in App only; App\**->*(*) matches every class below it.
  • Write pointcuts in single-quoted strings: backslashes need no escaping and $this->name is not interpolated.
  • An #[Around] advice returns the result. Return $invocation->proceed() unless you replace the result on purpose. Without the return the caller gets null, or PHP throws a TypeError ("none returned") when the advice declares a return type.
  • #[After] and #[Before] cannot change the result. #[After] runs like finally, also after an exception. #[AfterThrowing] gets the exception as the second parameter and cannot swallow it. To change a result or to handle an exception, use #[Around].
  • An exception thrown by a #[Before] advice skips everything else, the #[After] and #[AfterThrowing] advices of the same joinpoint included.
  • Aspects are never woven. An advice cannot intercept a method of an aspect, its own included.
  • An aspect must not advise the creation of its own dependencies. The aspect is built on the first advice call; if building it runs one of its advices, the framework throws AspectCircularReferenceException.
  • Properties: access(...) works for instance properties. Static, readonly and already hooked properties are not intercepted, and a pointcut that only matches those does nothing.
  • The kernel starts before the application classes are loaded, in every entry point: web, console, workers, tests. A bridge takes care of it; with a kernel of your own it is the init() call right after vendor/autoload.php. An entry point without it runs the application without aspects.

Performance in one paragraph

Aspects cost nothing where they do not apply: a method or property without advice in a woven class runs at full speed. An intercepted call costs about a third of a microsecond plus the advice itself, and booting the kernel in production about 0.15 ms per request, measured by the framework's benchmark. Production speed depends on running in production mode with a prebuilt cache and OPcache. Before answering a performance question or tuning a deployment, read references/performance.md: it has the measured numbers, their conditions and the checklist.

Reference files

ReadWhen
references/frameworks.mdThe application runs on Symfony, Laravel, Yii3 or another framework: installing the bridge, registering aspects, commands, deployment
references/setup.mdPlain PHP or no bridge: the kernel and its options, entry points, dependencies of aspects, tests, deployment, console commands
references/pointcuts.mdWriting or reviewing any pointcut that is not trivial
references/advices.mdJoinpoint methods, execution order, changing arguments and results, properties, functions, new, introductions, PHPStan generics
references/recipes.mdA complete aspect for logging, caching, transactions, retry, authorization, metrics, circuit breaker or rate limiting
references/performance.mdWhat aspects cost, production checklist, OPcache, preloading, containers, writing fast aspects
references/troubleshooting.mdAn advice does not run, an exception while weaving, stale cache, limitations

Aspect-oriented refactoring with Go! AOP

This skill turns code that already exists into aspects. The business methods keep what they are about, and the code that repeated around it moves into one place. It is a refactoring: the observable behaviour stays the same, and each step is small enough to verify.

It builds on the aspect-oriented-development skill of the same plugin, which describes the framework itself: pointcut syntax, advice types, joinpoints, registration of aspects, framework bridges, troubleshooting. Load that skill when a step here needs those details, and make sure the framework is installed and its kernel runs before you extract anything (its "Step 0").

The two smells

  • Scattering. One concern is implemented in many places: the same log call, the same permission check, the same try/catch in dozens of methods. Changing the concern means editing all of them.
  • Tangling. One method implements several concerns: a ten-line method with two lines of business logic between logging, a transaction and a cache lookup.

They come together, and an aspect removes both. A concern that is neither scattered nor tangled is not a candidate.

Workflow

Work through the steps in order. Steps 1 to 4 change nothing and end with a proposal to the user; do not start editing before they agreed to it.

1. Pin down the behaviour

A refactoring is only safe when a change of behaviour would be noticed. Run the framework in debug mode while you refactor: in production mode woven classes come from a cache, and your edits would have no effect until it is rebuilt.

Run the test suite and note the result. Where the methods you are going to touch have no tests, write characterization tests first, or at least a script that calls them and records everything observable: return values, exceptions, log records, queries, cache entries. The extracted code is mostly side effects, so a test that only checks return values proves little.

2. Scan

Search the source directories for code that repeats across methods, with whatever search and analysis tools you have. Leave the aspect classes of the project out: their advices repeat joinpoint calls by design. For every hit note the file, the method and where in the method it sits.

Look for three kinds of evidence:

  • Lines that repeat. Scattered code is copied code: the same statement shows up in many methods, apart from a string or a number (the message, the role, the TTL). Statements that call a logger, a connection, a cache, a security service or a clock are candidates. Statements that differ in what they are about (the same exec() call with a different query each time) only look alike and are business code.
  • The vocabulary of a concern. Each concern is made of a few calls: beginTransaction, commit, rollBack; isGranted; microtime. Searching for them finds the occurrences that are written differently in each place, and gives the list of files. references/catalog.md has the search terms per concern. Always search for what the user named, even when nothing else pointed at it: a concern can live in two methods only, or in one, such as a single retry loop.
  • Shapes. Some concerns are structure, not words: identical catch handlers, a try/finally around a whole method body, a loop that contains a try, the same first or last statement in many methods.

Then read the methods that came up most often from top to bottom. Tangling shows there: how many of their lines belong to the business logic, and how many to the candidates.

A list of hits does not answer two questions, so answer them by reading:

  • Are two hits one concern? beginTransaction() and the catch with rollBack() in the same methods are two halves of one concern. A permission check in those same methods is another concern that happens to guard them.
  • Where does the code sit? At the start of the method, at its end, around the work, or in the middle. A position is relative to the code as it is: a timer that starts after a cache lookup sits in the middle today, and at the boundary once the cache is an advice around it. Judge positions concern by concern, from the outside in.

3. Judge each candidate

Open the reported places and read them. For each candidate decide:

QuestionIf not
Is it the same concern in every place, not just similar text?Drop it, or split the group
Is it independent of the business logic around it? Would the method still be correct, only less observable, guarded or fast, without it?It is business logic: leave it, or use Extract Method
Does it sit at a method boundary: before the work, after it, or around it?"Extract an advice" has a preparatory step for fragments in the middle
Does it only need what a joinpoint offers: the arguments, the object, the result, the exception?See "What an advice can reach" in references/extract-advice.md
Is it in three or more places, or certain to spread?For one or two places an aspect costs more than it saves. Say so, but extract it when the user asked for that concern

Then name the concern and choose the advice type from where the code sits:

Where the repeated code sitsAdvice
Only before the work, needs arguments or the object#[Before]
Only before the work, and prevents it by throwing (guard, permission check)#[Before]
In a finally, or after the work whatever the outcome#[After]
In a catch that reports and rethrows#[AfterThrowing]
Before and after with shared state (start time, transaction, lock)#[Around]
Uses or replaces the result (cache, conversion)#[Around]
Catches and recovers, retries, or skips the work#[Around]

Prefer the weakest type that does the job: a #[Before] advice cannot forget to call proceed(). references/catalog.md lists the usual concerns with their code shapes, advice types and pitfalls.

4. Propose

Tell the user what you found before changing code: the concerns, where each one occurs (count and files), the aspect and marker attribute you would create for each, the advice type, what stays in the methods, and anything that would change behaviour (see "Keep the quirks" below). Recommend an order of extraction, as described in step 5.

5. Refactor, one concern at a time

Use the two refactorings. Each has its mechanics in a reference file; follow them step by step.

  • Refactor: Extract an aspect. A concern that is scattered over many methods moves into a new aspect, with a marker attribute on the methods. Read references/extract-aspect.md.
  • Refactor: Extract an advice. One fragment of a method, or of a few methods, moves into an advice of an existing or new aspect. This is the smaller step, and the building block of the first one. Read references/extract-advice.md.

Order. Among concerns that never meet on a method, start with the most scattered and least risky one, usually logging or timing. Where several concerns share methods, their order is given by the code: go from the outside in, and extract a guard (code that throws before the work starts) before any concern that reacts to exceptions. Otherwise the intermediate state differs from the original: an #[AfterThrowing] advice for failures would report the exception of a guard that is still in the method body, which the original try never saw. When such an intermediate difference cannot be avoided, predict it before the step and check that the diff is exactly that.

After every concern: run the tests or the characterization script, compare with step 1, and commit or otherwise checkpoint. Never extract two concerns in one step: when the output differs, you want one suspect.

6. Finish

Repeat the scan of step 2: the extracted lines are gone from the lists, and what remains is either the next concern or business code. Remove what the classes no longer need (see below), and report to the user what moved where.

Mark the code, do not match it from afar

An aspect acts at a distance: the method no longer shows what happens around it. The remedy is a marker attribute on the method and an attribute pointcut in the aspect.

#[Transactional]
#[RequiresRole('ROLE_ADMIN')]
public function cancel(int $orderId): void
#[Around('@execution(App\Attribute\Transactional)')]
  • The reader of the method sees every concern that applies, and "find usages" on the attribute lists all the places.
  • The attribute carries the settings that differed between the copies: the role, the TTL, the number of attempts.
  • A method opts in explicitly. A new method is not caught by accident, and renaming a class or method breaks nothing. Name patterns such as execution(public App\Service\*->save*(*)) fail in both ways; this is known as the fragile pointcut problem.

Use a name or namespace pointcut only when the rule really is "everything here, including future code", for example an audit log for every public method of a repository layer, and say so in the proposal.

Name the attribute after what it promises, not after how the aspect works: #[Transactional], #[Cacheable], #[Retry], #[RequiresRole], #[Loggable], #[Timed]. Put attributes in their own namespace (App\Attribute), aspects in theirs (App\Aspect), one aspect per concern.

Rules for a behaviour-preserving extraction

  • Keep the order. The original code ran its concerns in a sequence: log, then check, then open the transaction. Advices have their own: all #[Before] advices run first, then the #[Around] advices nest, each kind sorted by order (lower first, and outermost for #[Around]). Set order explicitly wherever two extracted concerns meet on one method, and write down why.
  • Keep the quirks, or ask. Copies of scattered code are rarely identical: one logs at another level, one caches null, one forgets the rollback. Decide per difference: it is a setting (attribute argument), a bug (ask the user), or a sign that the place is a different concern (leave it out). Do not silently unify. Extending a concern to methods that did not have it is a behaviour change too.
  • Replace what the fragment used. __METHOD__ becomes $method->class . '::' . $method->name from $invocation->getMethod(); func_get_args() becomes $invocation->getArguments(); $this becomes $invocation->getThis(), with access to its public members only.
  • Exceptions thrown by a #[Before] advice skip the other advices, including #[After] and #[AfterThrowing]. A guard that moved into a #[Before] advice is therefore not reported by an #[AfterThrowing] advice. Check that this matches the original order of guard and try.
  • Pick the tightest joinpoint. A retry loop around one call belongs on the method that makes the call, even a private one: every method can be advised, and calls through $this are intercepted.
  • Clean up afterwards. Remove constructor parameters, properties and use statements the class needed only for the extracted concern, and update the places that construct the class (container configuration, factories, tests). PHP ignores surplus arguments of a new call without any error, and a removed parameter in the middle shifts the following ones: find every construction, do not wait for a failure. A service that loses its logger and its security dependency is the visible benefit of the refactoring.

When not to extract

  • The code is business logic, even if it repeats: use ordinary refactorings.
  • The copies differ in more than a few settings: the "same" concern is several.
  • The fragment needs local variables from the middle of the method, and extracting a method around it would make the code worse.
  • The callers rely on seeing the behaviour, for instance an explicit transaction boundary that spans several calls and is committed by the caller.
  • The class cannot be woven: internal classes, code outside the include paths, classes loaded before the kernel.
  • The team does not want it. An aspect that the maintainers do not know about is worse than duplication.

Reference files

ReadWhen
references/extract-aspect.mdPerforming "Extract an aspect": mechanics, a complete before/after example, checklist
references/extract-advice.mdPerforming "Extract an advice": fragment position to advice type, what an advice can reach, fragments in the middle of a method, fragments that cannot be extracted
references/catalog.mdRecognizing a concern: code shapes, advice type, attribute, pitfalls; related refactorings (introductions, replacing decorators and base classes); lessons from AspectJ and Spring

Sponsors

Details

Marketplace
goaop/framework
Source
plugins/goaop
Category
Development
Keywords
php, aop, aspect, goaop