phasty/events

PHP 事件库

0.1 2015-11-18 07:45 UTC

This package is not auto-updated.

Last update: 2024-09-14 15:46:27 UTC


README

该包提供对不同类型对象的事件处理支持。要使用此功能,您只需将您的类继承自 Phasty\Events\Eventable 或在您的类中使用 Phasty\Events\EventableTrait 特性

class SomeCoolClass extends Phasty\Events\Eventable {
} 

$obj = new SomeCoolClass;
$obj->on("hello-event", function($event) {
    echo $event->getData();
});
$obj->trigger("hello-event", "Hello world");

输出

Hellow world!

更多内容

class Button extends Phasty\Events\Eventable {
    public function __construct() {
        $this->on("click", "sayHello");
        $this->on("click", "sayGoodbye");
    }
    protected function sayHello() {
        echo "Hello!\n";
    }
    protected function sayGoodbye() {
        echo "Bye!\n";
    }
    public function click() {
        $this->trigger("before-click");
        $this->trigger("click");
    }
}

$btn = new Button;
$btn->on("before-click", function () {
    echo "Before click handler\n";
});
$btn->click();
$btn->off("click", "sayHello");
$btn->click();

输出

Before click handler
Hello!
Bye!
Before click handler
Bye!

用法

// Listen to some-event
$obj->on("some-event", /* Any PHP callback or method name of $obj class */);
// Listen to any event
$obj->on(null, /* Any PHP callback or method name of $obj class */);
// Forget all events callbacks
$obj->off();
// Forget all callbacks of "some-event" event
$obj->off("some-event");
// Forget exact callback for "some-event"
$obj->off("some-event", /* Any PHP callback or method name of $obj class */);