Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Created June 20, 2014 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bayleedev/909703a2643f71cde953 to your computer and use it in GitHub Desktop.
Save bayleedev/909703a2643f71cde953 to your computer and use it in GitHub Desktop.
aspect oriented programming with traits in php
<?php
/**
* AOP Trait
* Used to created aop for your class.
*/
trait AOP {
public $filters = array();
public function applyFilter($method, $function) {
if (empty($this->filters[$method])) {
$this->filters[$method] = array();
}
return $this->filters[$method][] = $function;
}
public function _filter($method, $params, $callback) {
$callbacks = $this->filters[$method];
$callbacks[] = $callback;
$queue = new AOPChain($this, $callbacks);
return $queue->first($params);
}
}
/**
* Responsible for creating the chain queue and processing it
*/
class AOPChain {
public $host = null; // Object that has the filter
public $callbacks = array(); // array of callbacks
public function __construct($host, $callbacks) {
$this->host = $host;
$this->callbacks = $callbacks;
$this->position = 0;
}
// Helps with the first item in the chain by prependig known variables
public function first($params) {
return $this->next($this->host, $params, $this);
}
// called inside of a filter `$chain->next($self, $params, $chain);`
public function next($self, $params, $chain) {
return call_user_func($this->callbacks[$this->position++], $self, $params, $chain);
}
}
class Person {
use AOP;
public function address($name, $location) {
return $this->_filter(__FUNCTION__, compact('name', 'locations'), function($self, $params, $chain) {
echo 'Hello: '. $params['name'];
});
}
}
$foo = new Person();
$foo->applyFilter('address', function($self, $params, $chain) {
try {
$data = $chain->next($self, $params, $chain);
} catch (Exception $e) {
echo 'you caught something';
}
});
echo $foo->address('blaine', 'tulsa');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment