Re: Event-driven programming
Posted: Tue Jan 11, 2011 5:07 am
Something like this?
Code: Select all
<?php
class AOPizer
{
protected $object = null;
protected $beforeCallbacks = array();
protected $afterCallbacks = array();
public function __construct($object)
{
$this->object = $object;
}
public function __call($method, $args)
{
if (isset($this->beforeCallbacks[$method]))
foreach ($this->beforeCallbacks[$method] as $callback)
call_user_func_array($callback, array_merge(array($method), $args));
$result = call_user_func_array(array($this->object, $method), $args);
if (isset($this->afterCallbacks[$method]))
foreach ($this->afterCallbacks[$method] as $callback)
call_user_func_array($callback, array_merge(array($method), $args));
return $result;
}
public function before($method, $callback)
{
if (!isset($this->beforeCallbacks[$method]))
$this->beforeCallbacks[$method] = array();
$this->beforeCallbacks[$method][] = $callback;
}
public function after($method, $callback)
{
if (!isset($this->afterCallbacks[$method]))
$this->afterCallbacks[$method] = array();
$this->afterCallbacks[$method][] = $callback;
}
}
class User
{
public function save($username)
{
echo "User::save";
}
}
class Logger
{
public function log($method, $data)
{
echo "Logger::log ($method)";
}
public function getCallback()
{
return array($this, 'log');
}
}
$logger = new Logger();
$user = new AOPizer(new User());
$user->before('save', $logger->getCallback());
$user->after('save', $logger->getCallback());
$user->save('VladSun');