QIQ試してみた

前々から気になってたQIQを試してみました。

とりあえずPlaggerのrun_hookっぽい感じで。

<?php
class Pluggable {
    function loadPlugin($plugin, $to) {
        new $plugin($this, $to);
    }

    function registerHook() {
        foreach (func_get_args() as $hooks) {
            foreach ($hooks as $hook => $closure) {
                $this->hooks[$hook][] = $closure;
            }
        }
    }

    function runHook($hook) {
        foreach ($this->hooks[$hook] as $closure) {
            $closure();
        }
    }
}
// Pluginぽいの
class Pluggable_Plugin_Hello {
    function __construct($p, $to) {
        $this->to = $to;

        $self = $this; // $this は static $this で取り込めないようなので
        $p->registerHook(
            array(
                'hello_hook' => function() { echo "hello\n"; }
            ),
            array(
                'buy_hook' => static function() {
                    static $self;
                    $self->buy();
                }
            )
        );
    }

    function buy() {
        echo "buy {$this->to}\n";
    }
}

んで実行してみる。

<?php
$p = new Pluggable;
$p->loadPlugin('Pluggable_Plugin_Hello', 'id:taraburo');
$p->runHook('hello_hook');
$p->runHook('buy_hook');
hello
buy id:taraburo

PHPでも変態になれそう。。。