PHP code example of xtompie / aop

1. Go to this page and download the library: Download xtompie/aop library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xtompie / aop example snippets




namespace Xtompie\Aop;

interface Aspect
{
    public function order(): float;
    public function joinpoint(string $joinpoint): bool;
    public function advice(Invocation $invocation): mixed;
}



use Xtompie\Aop\GenericAspect;

class DebugAspect implements GenericAspect
{
    protected function pointcuts(): array
    {
        return [
            'FoobarService::*',
        ];
    }

    public function advice(Invocation $invocation): mixed
    {
        $result = $invocation();
        var_dump([
            'AOP',
            'joinpoint' => $invocation->joinpoint(),
            'args' => $invocation->args(),
            'result' => $result,
        ]);
        return $result;
    }
}



use Xtompie\Aop\Aop;

$aop = new Aop([
    new DebugAspect(),
]);

function aop(string $joinpoint, array $args, callable $main): mixed
{
    return $GLOBALS['aop']->__invoke($joinpoint, $args, $main);
}



class FoobarService
{
    public function baz(int $a): int
    {
        return aop(__METHOD__, func_get_args(), function(int $a) { // <-- added line
            return $a + 1;
        }); // <-- added line
    }
}



use Xtompie\Aop\GenericAspect;

class AddFiveAspect implements GenericAspect
{
    protected function pointcuts(): array
    {
        return [
            'FoobarService::__invoke',
        ];
    }

    public function advice(Invocation $invocation): mixed
    {
        $invocation = $invocation->withArgs([$invocation->args()[0] + 5]);
        return $invocation();
    }
}



use Xtompie\Aop\GenericAspect;

class AddFiveAspect implements GenericAspect
{
    public function order(): float
    {
        return 10;
    }

    // ...
}



use Xtompie\Aop\GenericAspect;

class MinusTeenAspect implements GenericAspect
{
    public function order(): float
    {
        return 999;
    }

    protected function pointcuts(): array
    {
        return [
            'FoobarService::__invoke',
        ];
    }

    public function advice(Invocation $invocation): mixed
    {
        return $invocation->args()[0] - 10;
    }
}