Skip to content

Instantly share code, notes, and snippets.

@lisachenko
Created May 25, 2013 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lisachenko/5650454 to your computer and use it in GitHub Desktop.
Save lisachenko/5650454 to your computer and use it in GitHub Desktop.
Preview of privileged advices in the Go! AOP PHP framework
<?php
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Annotation\Around;
/**
* Privileged aspect shows the power of privileged advices.
*
* Privileged advice is running in the scope of target for the current joinpoint
*/
class PrivilegedAspect implements Aspect
{
/**
* Privileged advice, pay an attention to the 'scope="target"' in the annotattion
*
* @Around("execution(public Test->method(*))", scope="target")
*
* @param MethodInvocation $invocation
* @return mixed|null|object
*/
protected function aroundMethodExecution(MethodInvocation $invocation)
{
echo "In the around() hook", PHP_EOL;
/** @var Test $this */
echo get_class($this), PHP_EOL; // 'Test', not the 'PrivilegedAspect'
echo $this->message, PHP_EOL; // We are running in the scope of target, so we can easily access protected fields
$obj = new static(); // $obj will be instance of 'Test' class or it children, according to the LSB
// $invocation->proceed(); Prevent an execution of the original method Test->method()
$obj->tryToCallMe(); // Instead of original method, we are calling the protected method tryToCallMe()
// from another instance of Test class ($obj)!
}
}
<?php
class Test
{
protected $message = 'Try to get me!';
public function method()
{
echo 'Hello, AOP!', PHP_EOL;
}
protected function tryToCallMe()
{
echo 'Yahoo ' . $this->message, PHP_EOL;
}
}
<?php
// .. AOP initialization here, registration of PrivilegedAspect in the kernel
$test = new Test();
$test->method();
/**
* Output will be:
*
* In the around() hook
* Test
* Try to get me!
* Yahoo Try to get me!
*/
@lisachenko
Copy link
Author

Documentation about privileged advices is available at http://go.aopphp.com/docs/privileged-advices/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment