Photon comes with an experimental library to perform some basic AOP. It uses proxies (similar to SpringAOP) to implement the advice. Unfortunately, you have to manually apply the 'weave' method to any objects that might need to be advised.
Here is a basic example that shows how to use it:
Example 6.1. AOP
<?php
// some business object
class BusinessAction {
function prepare ($p1, $p2) {
echo "== PREPARE METHOD CALLED [$p1, $p2] \n";
}
function execute ($p1) {
echo "== EXECUTE METHOD [$p1] \n";
return true;
}
}
require_once 'photon/aspect/Advice.php';
class LoggingAdvice extends Advice {
function before ($method, $params) {
echo "Before calling [$method] with params: ".var_export($params, true)."\n";
}
function after ($method, $return) {
echo "After calling [$method] which returned: ".var_export($return, true)."\n";
}
function around (MethodInvocation $m) {
echo "Around method start\n";
// here we can actually replace parameters
$params = $m->getParams();
$params[0] = 'replaced';
$m->setParams($params);
// allow the method to proceed
$return = $m->proceed();
echo "Around method end\n";
// we can also replace the return value
$return = 'replaced return';
return $return;
}
}
// create an aspect weaver
require_once 'photon/aspect/AspectWeaver.php';
$aop = new AspectWeaver;
// configure a pointcut to attach logging advice to all classes and all methods
$aop->add('*->*', new LoggingAdvice);
$action = new BusinessAction;
// manually weave the advice into the action
// (sorry, that's the best i can do right now without actually exending the language)
$aop->weave($action);
// call the methods normally now
$action->prepare('param1', 'param2');
$action->execute(24);
Example 6.2. Output
Before calling [prepare] with params: array ( 0 => 'param1', 1 => 'param2', ) Around method start == PREPARE METHOD CALLED [replaced, param2] Around method end After calling [prepare] which returned: 'replaced return' Before calling [execute] with params: array ( 0 => 24, ) Around method start == EXECUTE METHOD [replaced] Around method end After calling [execute] which returned: 'replaced return'
Example 6.3. Authentication Advice
<?php
// let's create some advice that checks that a user is logged in before showing a page
require_once 'photon/aspect/Advice.php';
class AuthAdvice extends Advice {
function around (MethodInvocation $m) {
$user = $_SESSION['user'];
if (!$user) {
$params = $m->getParams();
$params[0] = '/sign_in';
$m->setParams($params);
}
return $m->proceed();
}
}
// create a new PageControllerApp
$app = new PageControllerApp(...);
$aop = new AspectWeaver;
$aop->add('*->run', new AuthAdvice);
$aop->weave($app);
$app->run();
?>