Skip to content

Instantly share code, notes, and snippets.

@swvitaliy
Created February 4, 2012 16:34
Show Gist options
  • Save swvitaliy/1738830 to your computer and use it in GitHub Desktop.
Save swvitaliy/1738830 to your computer and use it in GitHub Desktop.
Simple producer-consumer pattern implementation
<?php
/**
* events.php
* Простая реализация паттерна producer-consumer (Listener)
*
* Author: swvitaliy
*/
class Listener {
private $func = null;
private $lastResult = null;
public function __construct ($func)
{
$this->func = $func ? new ReflectionFunction($func) : null;
}
public function getLastResult ()
{
return $this->lastResult;
}
public function __invoke ()
{
return $this->lastResult = $this->func ?
$this->func->invokeArgs(func_get_args()) : null;
}
}
class Producer {
protected $listeners = array (
// 'callable_method' => object Listener
);
public function callListeners ($event)
{
$args = func_get_args();
array_shift($args);
foreach ($this->listeners[$event] as $v)
call_user_func_array($v, $args);
}
public function addListener ($event, $action)
{
if (!isset($this->listeners [$event]))
$this->listeners [$event] = array();
$this->listeners [$event][] = new Listener($action);
}
public function addListeners ($event, $actions)
{
foreach ($actions as $action)
$this->addListener($event, $action);
}
public function clearListeners ()
{
if (isset($this->listeners [$event]))
$this->listeners [$event] = array();
}
public function getListeners ($event, $default = FALSE)
{
return isset($this->listeners [$event]) ?
$this->listeners [$event] : $default;
}
}
/*
class Obj {
public function getProducer ()
{
return empty($this->producer)
? $this->producer = new Producer : $this->producer;
}
}
class O1 extends Obj {
public function a() {
echo "call O1::a\n";
$this->getProducer()->callListeners('a');
}
}
$o1 = new O1;
$o1->getProducer()->addListener('a',
function () {
echo "call Listener \n";
});
$o1->a();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment