This demo shows your an examples of AOP usage.
Please, choose one of available examples from navigation menu.
You can also try to run this code with XDebug.
Calling After Interceptor for get(Demo\Example\PropertyDemo->indirectModificationCheck), value: [4,5,6] Calling Around Interceptor for execution(array_push()) with arguments: [[4,5,6],7,8,9] Calling After Interceptor for get(Demo\Example\PropertyDemo->indirectModificationCheck), value: [4,5,6,7,8,9] Calling After Interceptor for get(Demo\Example\PropertyDemo->publicProperty), value: 123 123Calling After Interceptor for set(Demo\Example\PropertyDemo->publicProperty), value: 987 Calling After Interceptor for get(Demo\Example\PropertyDemo->protectedProperty), value: 456 456 Calling After Interceptor for set(Demo\Example\PropertyDemo->protectedProperty), value: 987
<?php
/*
* Go! AOP framework
*
* @copyright Copyright 2014, Lisachenko Alexander <lisachenko.it@gmail.com>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace Demo\Aspect;
use Go\Aop\Aspect;
use Go\Aop\Intercept\FieldAccess;
use Go\Lang\Annotation\Around;
/**
* Property interceptor can intercept an access to the public and protected properties
*
* Be aware, it's very tricky and will not work for indirect modification, such as array_pop($this->property);
*/
class PropertyInterceptorAspect implements Aspect
{
/**
* Advice that controls an access to the properties
*
* @param FieldAccess $fieldAccess Joinpoint
*
* @Around("access(public|protected Demo\Example\PropertyDemo->*)")
* @return mixed
*/
public function aroundFieldAccess(FieldAccess $fieldAccess)
{
$isRead = $fieldAccess->getAccessType() == FieldAccess::READ;
// proceed all internal advices
$fieldAccess->proceed();
if ($isRead) {
// if you want to change original property value, then return it by reference
$value = /* & */$fieldAccess->getValue();
} else {
// if you want to change value to set, then return it by reference
$value = /* & */$fieldAccess->getValueToSet();
}
echo "Calling After Interceptor for ", $fieldAccess, ", value: ", json_encode($value), PHP_EOL;
}
}
<?php
/*
* Go! AOP framework
*
* @copyright Copyright 2014, Lisachenko Alexander <lisachenko.it@gmail.com>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace Demo\Example;
/**
* Example class to show how to intercept an access to the properties
*/
class PropertyDemo
{
public $publicProperty = 123;
protected $protectedProperty = 456;
protected $indirectModificationCheck = [4, 5, 6];
public function showProtected()
{
echo $this->protectedProperty, PHP_EOL;
}
public function setProtected($newValue)
{
$this->protectedProperty = $newValue;
}
public function __construct()
{
array_push($this->indirectModificationCheck, 7, 8, 9);
if (count($this->indirectModificationCheck) !== 6) {
throw new \RuntimeException("Indirect modification doesn't work!");
}
}
}