Do You PHP はてブロ

Do You PHPはてなからはてブロに移動しました

PEAR::Event_SignalEmitter

「シグナル」を扱うためのパッケージで、バージョン0.3.0がリリースされています。まだβ版ですが、ネーミングが気になったのでさっくり見てみました。つか、emitなんて単語を見たの、多分大学以来だw


Generic signal emitting class with the same API as GObject.
Since GObject doesn't allow classes to define or emit own signals,
this class provides a PHP implementation with the same API.

試したコードは、パッケージに付属するサンプル dispatcher.phpを若干修正したものです。

<?php
/**
*   Using the dispatcher class
*/
require_once 'Event/SignalEmitter/Dispatcher.php';

$dp = Event_SignalEmitter_Dispatcher::singleton();
$dp->register_signal('download-begin');
$dp->register_signal('download-progress');
$dp->register_signal('download-complete');

class Logger
{
    public function log() {
        $args = func_get_args();
        if (is_array($args[0])) {
            $str = implode(' / ', $args[0]) . ' / ' . $args[1];
        } else {
            $str = implode(' / ', $args);
        }
        echo 'Log: ' . $str . "\n";
    }
}

class Downloader
{
    public function download($file) {
        echo "Beginning download\n";
        //simulate some downloading process
        $dp = Event_SignalEmitter_Dispatcher::singleton();
        for ($nA = 0; $nA < 100; $nA += 10) {
            $dp->emit('download-progress', array($file, $nA));
        }
        $dp->emit('download-complete', $file);
    }
}


$l = new Logger();
$d = new Downloader();

$dp->connect_simple('download-begin'   , array($l, 'log'), 'begin download');
$dp->connect_simple('download-progress', array($l, 'log'), 'progress');
$dp->connect_simple('download-complete', array($l, 'log'), 'download complete');
$dp->connect_simple('download-begin'   , array($d, 'download'));


$dp->emit('download-begin', 'http://some.where/over/the/rainbow.htm');

これを実行すると、

$ php dispatcher.php
Log: http://some.where/over/the/rainbow.htm / begin download
Beginning download
Log: http://some.where/over/the/rainbow.htm / 0 / progress
Log: http://some.where/over/the/rainbow.htm / 10 / progress
Log: http://some.where/over/the/rainbow.htm / 20 / progress
Log: http://some.where/over/the/rainbow.htm / 30 / progress
Log: http://some.where/over/the/rainbow.htm / 40 / progress
Log: http://some.where/over/the/rainbow.htm / 50 / progress
Log: http://some.where/over/the/rainbow.htm / 60 / progress
Log: http://some.where/over/the/rainbow.htm / 70 / progress
Log: http://some.where/over/the/rainbow.htm / 80 / progress
Log: http://some.where/over/the/rainbow.htm / 90 / progress
Log: http://some.where/over/the/rainbow.htm / download complete
$ 

な感じ。発生しうるシグナル(イベントに名前を付けたもの?)を登録しておいて、コールバックを使って呼び出している感じですね。
説明に「Generic signal emitting class」とあるので、他のパッケージから使われることを想定していそうな雰囲気がするんですが、どの辺のパッケージと繋がるんだろ?