Skip to content

Instantly share code, notes, and snippets.

@kanonji
Created April 7, 2018 06:42
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 kanonji/a4dfa75b68f4e69e0dddc5c618e0aa28 to your computer and use it in GitHub Desktop.
Save kanonji/a4dfa75b68f4e69e0dddc5c618e0aa28 to your computer and use it in GitHub Desktop.
<?php
class SimpleDelegate {
protected $callbacks = [];
public function add(Closure $callback, $key = null){
$key = $key?: spl_object_hash($callback);
$this->callbacks[$key] = $callback;
}
public function remove(Closure $callback){
$key = spl_object_hash($callback);
unset($this->callbacks[$key]);
}
public function removeByKey($key){
unset($this->callbacks[$key]);
}
public function __invoke() {
$results = [];
foreach($this->callbacks as $callback){
$results[] = call_user_func_array($callback, func_get_args());
}
return $results;
}
}
class Foo{
private $delegate;
private $counter = 0;
private $text1 = '';
private $text2 = '';
private $text3 = '';
public function __construct(){
$this->delegate = new SimpleDelegate;
$this->delegate->add(function($arg){
$this->privateMethod($arg);
});
$callback2 = function($arg){
$this->privateMethod2($arg);
};
$callback3 = function($arg){
$this->privateMethod3($arg);
};
$this->delegate->add($callback2);
$this->delegate->add($callback3);
$this->delegate->remove($callback2);
$this->delegate->__invoke('abc.');
$this->delegate->__invoke('ABC.');
$this->delegate->__invoke('AAA.');
}
private function privateMethod($arg){
$this->counter++;
$this->text1 .= $arg;
}
private function privateMethod2($arg){
$this->text2 .= $arg;
}
private function privateMethod3($arg){
$this->text3 .= $arg;
}
}
var_dump(new Foo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment