Keep your business logic clean. Make your methods powerful. Go! AOP attaches reusable behaviors to any method of your application — logging, caching, transactions, authorization, audit and more — without changing your original code. You write a behavior once, in an ordinary PHP class, and say where it applies: with an attribute on a method or with a matching rule. The framework then applies it as dynamic middleware around every selected method when PHP loads the class.
Define such behaviors once, and apply them automatically everywhere they are needed. Your business logic stays clean, your infrastructure code stays organized.
Your class carries only its business logic and, if you like, an attribute of your own:
use App\Attribute\Transactional;
final class OrderService
{
#[Transactional]
public function placeOrder(Order $order): void
{
// business logic only
}
}The behavior lives in a behavior class (an aspect, in the API) and runs around every method that carries the attribute:
use App\Attribute\Transactional;
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Around;
final class TransactionAspect implements Aspect
{
public function __construct(private readonly \PDO $connection) {}
#[Around('@execution(App\Attribute\Transactional)')]
public function inTransaction(MethodInvocation $invocation): mixed
{
$this->connection->beginTransaction();
try {
$result = $invocation->proceed();
$this->connection->commit();
return $result;
} catch (\Throwable $exception) {
$this->connection->rollBack();
throw $exception;
}
}
}Register the behavior class in the kernel once (see Installation), and every method marked
#[Transactional] runs in a transaction. OrderService keeps its name, its final declaration and its type: there
is no wrapper object and no decorator to wire.
-
No PECL/PIE extensions required — Forget about
php-aop,runkit,uopz, or any other low-level extensions. Go! AOP is written in 100% pure PHP — justcomposer requireand you're ready. No compilation, no system dependencies, no deployment headaches. -
Zero
eval()calls — Your architecture team will love this. The framework never useseval()orcreate_function()for dynamic code execution. Applying behaviors produces static PHP files that can be reviewed, scanned by security tools, and audited. No hidden code generation at runtime. -
PHPStan Level 10 — The entire codebase passes PHPStan's strictest analysis level — maximum type safety, no mixed types escaping, full type-aware support. This means fewer bugs, better IDE autocompletion, and confidence that the framework won't introduce type errors into your application.
The framework provides powerful core interception capabilities that hook your behaviors into almost any place in your application — even into the methods PHP won't let you override:
| Where a behavior can run | Support |
|---|---|
| Public & protected methods | ✅ |
| Static and final methods | ✅ |
| Private methods | ✅ |
Methods in final classes |
✅ |
| Trait methods | ✅ |
| Enum methods (PHP 8.1+) | ✅ |
| Property reads and writes | ✅ |
Object creation with new |
✅ |
| Calls of system functions | ✅ |
| Before, After, AfterThrowing and Around | ✅ |
Function calls and object creation are intercepted in the code the framework transforms, see Behaviors.
Behaviors can run on property reads and writes too: Go! AOP intercepts field access via native PHP 8.4 property hooks on generated proxy classes.
- Supported targets:
- properties declared in the woven class itself, including constructor-promoted properties (also
finalones, PHP 8.5): the assignment made by the constructor is intercepted as a write - inherited public/protected properties from parent classes
- properties declared in the woven class itself, including constructor-promoted properties (also
- Not supported (intentionally skipped):
static,readonly, and already-hooked properties- inherited
finalproperties from parent classes - inherited
privateproperties
For array-typed intercepted properties, the proxy emits only a by-reference &get hook (without set) to keep
indirect modification operations like array_push($this->items, ...) valid.
Generated hooks pass values to the field access joinpoint by value (read()/write()), only the &get hook of
array properties uses readByReference(). For typed properties without a default value, generated hooks include an
initialization guard:
if (isset($this->property) || $__joinPoint->getField()->isInitialized($this)) {
return $__joinPoint->read($this, $this->property);
} else {
return $__joinPoint->read($this);
}See also: PHP 8.4 Feature Support & Known Limitations for detailed information about property hooks, readonly properties, lazy objects, and other PHP 8.4 features.
PHP 8.5 Feature Support & Known Limitations covers the PHP 8.5 audit results.
-
Expressive matching rules — Say where a behavior runs with an intuitive, readable grammar (pointcuts, in the API). Select methods by visibility, name patterns, attributes, class hierarchy, and more — all in a single expression like
execution(public **->save*(*)). -
Full Xdebug support: breakpoints work in your original code — Unlike other AOP solutions that generate unreadable proxy code, the framework produces clean, debuggable PHP. Set breakpoints directly in your behaviors or in your original classes — step through code naturally, inspect variables, and debug as if the behaviors were written by hand.
-
Code stays readable — No magic methods, no
__call()indirection and no objects wrapping your instances at runtime. The transformed source is plain PHP that you can read, understand, and audit. What you see in the cache is what gets executed. -
Attributes are kept — Attributes of a class with behaviors and of its methods, parameters, constants and properties are copied to the generated code from your source, with their original arguments: enum cases,
newexpressions, closures and first-class callables included. Reading attributes at runtime works on such classes exactly as before. -
Framework-agnostic — integrates with popular frameworks and vanilla PHP. Works equally well in legacy applications or greenfield projects — no architectural changes required.
-
Lightning fast — Quick start in just a few ms. Behavior classes are initialized once and cached, so subsequent requests have virtually no initialization overhead.
-
Opcode cache friendly — First-class support for OPcache. Transformed files and classes are stored as plain PHP files, fully optimized by your opcode cache just like regular code.
-
Smart caching — Behaviors are attached as first-class callables pointing straight at the methods of your behavior classes, and call contexts are resolved at compile time and cached in the generated code — eliminating runtime reflection costs and lazy advisor indirection.
-
Zero cost for code without behaviors. Under 1 µs for code with them. — No runtime attribute parsing, no slow
__callmethods, no proxy objects wrapping your instances. Method interception happens through direct, inlined PHP code, and methods without behaviors cost nothing. The numbers are in Performance. -
No build step in development — Classes are transformed when PHP loads them. One cache warm-up command for production.
Some code refuses to stay in one class. Logging, caching, security checks, transactions and performance monitoring end up copied into dozens or hundreds of methods, mixed with the business logic they surround:
- Logging — you need it in dozens of methods across your application
- Caching — scattered throughout services and repositories
- Security checks — repeated before every sensitive operation
- Transaction management — wrapping multiple database operations
- Performance monitoring — measuring execution time everywhere
You end up copying the same code into hundreds of places, and when requirements change, you hunt through the entire codebase. This is called code scattering and code tangling — and it violates the DRY principle at scale.
PHP developers already know the answer from their HTTP stack: middleware. A middleware is written once and runs around every request, and the controllers know nothing about it. Go! AOP brings the same idea to any method, property or object creation in your code:
- Write the behavior once, as a method of a behavior class. It receives the call context and decides what happens before, after or instead of the original call.
- Say where it applies with a matching rule in the behavior's attribute: every method marked
#[Transactional], every public method belowApp\Service, every read and write ofUser->email. - The framework applies it. When PHP loads a class, Go! AOP finds the behaviors whose rules match its members and attaches them around those members as a chain of middleware. This step is called weaving. Your source files are never modified.
The attribute on a behavior says when it runs relative to the intercepted call:
| Attribute | Runs | Example use |
|---|---|---|
#[Before] |
Before the call. It can change the arguments. | Validate input, check permissions |
#[After] |
After the call, also when it throws (like finally) |
Release resources, stop timers |
#[AfterThrowing] |
When the call throws. The exception is rethrown afterwards | Log errors, send alerts |
#[Around] |
Instead of the call, like a middleware: it decides whether to call proceed(), and its return value becomes the result |
Caching, transactions, retry logic |
Around is the most powerful one — it controls whether the original method runs at all, can modify arguments, change return values, or handle exceptions.
Behaviors can do more than wrap calls: a behavior class can also add new capabilities to existing classes, an
interface together with a trait that implements it. Want all your DTOs to implement JsonSerializable? Declare it
once in a behavior class, and Go! AOP adds the interface and the implementation to every matching class. No base
classes, no copied code.
Under the hood, Go! AOP is an aspect-oriented programming (AOP) framework, and its API keeps the classic AOP names: you meet them in code, in class names and in error messages. The technical parts of this README and the documentation use them too:
| In everyday words | In the API | What it is | Real-world analogy |
|---|---|---|---|
| Behavior class | Aspect | A class that implements Go\Aop\Aspect and groups related behaviors |
A chapter in a guidebook covering the document signing process |
| Behavior (middleware) | Advice | A public method of the behavior class with one attribute from Go\Lang\Attribute: #[Before], #[After], #[AfterThrowing] or #[Around] |
The specific guidance: "Before signing the document, read everything" |
| Matching rule | Pointcut | The expression in that attribute that selects where the behavior runs | The rule for when advice applies: "Before signing any contract" |
| Call context | Joinpoint | The intercepted moment (a method call, a property access, object creation), passed to the behavior as an object | A decision point in your day where advice could apply |
| Applying behaviors | Weaving | Turning your classes into the files PHP loads, with the behaviors attached as middleware | The mentor's words becoming part of your thinking |
| Class extension | Introduction | An interface and a trait added to existing classes | Learning a new skill without changing who you are |
Why "advice"? Think of life advice. Your mentor doesn't follow you around repeating "check your inputs before every decision." Instead, they give you one piece of advice that you apply in many situations. A behavior works the same way — you write it once, and the framework applies it at the right moments.
No build step in development. One cache warm-up command for production. Go! AOP applies behaviors at load time: when PHP loads a class, the framework transforms its source, attaches the
middleware and stores the result as plain PHP files in a cache directory. There is no PECL extension, no eval(), no
build tool to run while you develop and no generated files to commit, and your original source files stay untouched.
In production, build the whole cache at deploy time with vendor/bin/aspect cache:warmup:aop, see
Deployment.
Upgrading from 3.x? Follow the upgrade guide.
Go! AOP can be installed with composer. Getting started takes five steps:
- Download the framework using composer
- Create the application kernel (an aspect kernel)
- Initialize the kernel in the front controller
- Write a behavior class (an aspect)
- Register the behavior class in the kernel
Step 0 is optional: it lets you try the demo examples first.
The demos are not part of the composer package, so clone the repository and install its dependencies:
git clone https://github.com/goaop/framework.git
cd framework
composer install
php -S localhost:8080 -t demosThen open http://localhost:8080 in your browser and look at the demo examples before installing the framework in your project.
Ask composer to download the latest version of Go! AOP framework with its dependencies by running the command:
composer require goaop/frameworkComposer will install the framework to your project's vendor/goaop/framework directory.
The kernel is the single place where your application configures its behaviors.
You have to first create an AspectKernel class
for your application. This class manages all behavior classes (aspects) of your
application in one place.
The framework provides base class to make it easier to create your own kernel.
To create your application kernel, extend the abstract class Go\Core\AspectKernel
<?php
// app/ApplicationAspectKernel.php
use Go\Core\AspectKernel;
use Go\Core\AspectContainer;
/**
* Application Aspect Kernel
*/
class ApplicationAspectKernel extends AspectKernel
{
/**
* Configure an AspectContainer with advisors, aspects and pointcuts
*/
protected function configureAop(AspectContainer $container): void
{
}
}To configure the kernel, call the init() method of the kernel instance.
<?php
// public/index.php
include __DIR__ . '/../vendor/autoload.php'; // use composer
// Initialize an application aspect container
$applicationAspectKernel = ApplicationAspectKernel::getInstance();
$applicationAspectKernel->init([
'debug' => true, // use 'false' for production mode
'appDir' => __DIR__ . '/..', // Application root directory
'cacheDir' => __DIR__ . '/../var/cache/aop', // Cache directory
// Include paths restricts the directories where behaviors should be applied, or empty for all source files
'includePaths' => [
__DIR__ . '/../src/'
]
]);A behavior class (an aspect, in the API) is a simple PHP class that implements Go\Aop\Aspect, so you can use all
features of OOP in it: constructor injection, private state, traits.
Its behaviors (advices) are declared as public methods with an attribute — the framework attaches them to your code as first-class callables, so every behavior must be callable on the instance from the outside (a protected or private advice method is rejected when the aspect is loaded).
As an example, let's intercept all the methods of a class and display their names:
<?php
// Aspect/MonitorAspect.php
namespace Aspect;
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Before;
/**
* Monitor aspect
*/
class MonitorAspect implements Aspect
{
/**
* Method that will be called before real method
*/
#[Before("execution(public Example->*(*))")]
public function beforeMethodExecution(MethodInvocation $invocation): void
{
echo 'Calling Before Interceptor for: ',
$invocation,
' with arguments: ',
json_encode($invocation->getArguments()),
"<br>\n";
}
}Easy, isn't it? We declared here that the behavior runs before the execution of
all dynamic public methods in the class Example. The matching rule (a pointcut) is the argument of
the attribute #[Before("execution(public Example->*(*))")].
The other attributes are listed in When a behavior runs.
There is no magic behind applying a behavior. For every intercepted method the framework generates a plain, debuggable interceptor chain — the middleware chain — in which each advice is referenced as a closure created with first-class callable syntax right on the aspect instance:
static $__joinPoint = InterceptorInjector::forMethod(
self::class,
'doSomething',
[
Interceptor::before(The::aspect(MonitorAspect::class)->beforeMethodExecution(...)),
],
$this->doSomethingOriginalAlias(...),
);The::aspect() fetches the aspect instance from the aspect container, and
->beforeMethodExecution(...) is the very advice method you wrote above — you can
Ctrl-click it in your IDE, set a breakpoint inside it, and step through the generated code as if
it were handwritten. This direct wiring is the main way behaviors are applied.
Advices that are registered in the container as plain closures (rather than aspect methods)
are attached through the lazy The::advice() accessor instead, which resolves the advisor by
its identifier and unwraps it down to the raw advice closure:
Interceptor::around(The::advice('advisor.Demo\Aspect\DynamicMethodsAspect->aroundMagicMethods')),A behavior class is a typical container service of the aspect container. Add it in the configureAop() method of the
kernel, either eagerly as an instance or - preferably - as a deferred definition that is
only constructed when one of its behaviors actually runs:
<?php
// app/ApplicationAspectKernel.php
use Aspect\MonitorAspect;
use Go\Core\AspectContainer;
//...
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());
// Dependencies from the PSR-11 container of your application, attached later via setDelegate():
// $container->addLazyService(MonitorAspect::class, static fn(AspectContainer $c) => new MonitorAspect($c->getService(LoggerInterface::class)));
}
//...Doctrine ORM (3.6+) maps a woven entity as is: the woven class keeps its name and all mapping attributes, and the original class body lives in a trait that Doctrine never maps. Two things need to be configured.
Entity discovery. Given plain directories, Doctrine includes the entity source files directly,
which bypasses the weaver (the entity loses its behaviors), and it misses entities that were already
loaded through the autoloader. Let the mapping driver discover entities through
Go\Bridge\Doctrine\WovenEntityClassLocator instead: it reads class names from the source files
and loads each class through the autoloader, which serves the woven version.
use Doctrine\ORM\Mapping\Driver\AttributeDriver;
use Go\Bridge\Doctrine\WovenEntityClassLocator;
$configuration->setMetadataDriverImpl(
new AttributeDriver(WovenEntityClassLocator::createFromDirectories([__DIR__ . '/src/Entity'])),
);Intercepted properties. An intercepted property is re-declared with native property hooks,
which Doctrine supports only with native lazy objects. Enable them and, optionally, register
Go\Bridge\Doctrine\MetadataLoadInterceptor, which reports a woven entity with intercepted mapped
properties when native lazy objects are off, instead of failing on the first lazy proxy:
use Doctrine\ORM\Events;
use Go\Bridge\Doctrine\MetadataLoadInterceptor;
$configuration->enableNativeLazyObjects(true);
$eventManager->addEventListener(Events::loadClassMetadata, new MetadataLoadInterceptor());Doctrine reads and writes the raw property values while hydrating and flushing, so property behaviors only run for accesses made by your own code, never for Doctrine's internal ones.
- Configuration and deployment: kernel options,
Featuresflags, thebin/aspectconsole commands, the production deployment recipe and custom transformers or node rewriters - Matching rules: the pointcut syntax — every pointcut type, wildcards, modifiers, return types and operators
- Behaviors: advice types, joinpoints, property interception, introductions, function and object-creation interception
- Performance: measured costs of the modes, the optimizations behind them, cache warm-up, OPcache tuning, Docker and Kubernetes
- PHP 8.4 limitations and PHP 8.5 limitations
- Upgrading from 3.x and the changelog
The repository is a plugin marketplace for coding agents. The goaop plugin holds two Agent Skills:
- aspect-oriented-development teaches an agent to write behavior classes, matching rules and behaviors (aspects, pointcuts and advices), to integrate the framework into an application, to deploy the cache, to reason about performance and to find out why a behavior does not run;
- aspect-oriented-refactoring teaches it to convert existing code: to find logic repeated across many methods, to decide what belongs in a behavior class and to extract it without changing what the code does.
/plugin marketplace add goaop/framework
/plugin install goaop@goaop
Other agents and the copy that ships with the composer package: plugins/goaop.
To contribute changes, see the contributing guide