romeoz/rock-events

A simple implementation of Pub/Sub for PHP

0.11.0 2015-11-06 03:06 UTC

This package is not auto-updated.

Last update: 2024-11-19 04:47:46 UTC


README

Latest Stable Version Total Downloads Build Status HHVM Status Coverage Status License

Features

  • Handler can be a closure, instance, and static class
  • Standalone module/component for Rock Framework

Installation

From the Command Line:

composer require romeoz/rock-events

In your composer.json:

{
    "require": {
        "romeoz/rock-events": "*"
    }
}

Quick Start

use rock\events\Event;

class Foo 
{
    public $str = 'Rock!';
}

$object = new Foo();
$eventName = 'onAfter';
$handler = function (Event $event) {
    echo "Hello {$event->owner->str}"; 
};

Event::on($object, $eventName, $handler);

Event::trigger($object,  'onAfter'); // output: Hello Rock!

Documentation

####on(string|object $class, string $name, callable $handler)

To subscribe to the event.

Set a handler can be as follows:

$handler = function (Event $event) { 
    echo "Hello Rock!"; 
};
Event::on(new Foo, 'onAfter', $handler);

Options:

  • function (Event $event) { ... }
  • [new Foo, 'method']
  • ['Foo', 'static_method']

####trigger(string|object $class, string $name, Event $event = null)

To publish event.

Event::trigger(new Foo,  'onEvent'); 

// or

Event::trigger('test\Foo',  'onEvent');

####off(string|object $class, string $name, callable $handler = null)

Detach event.

$handler = 
    function (Event $event) {
        echo 'Hello Rock!'
    };
$instance =  new Foo;
Event::on($instance, 'onAfter', $handler);

Event::off($instance, 'onAfter');

Requirements

  • PHP 5.4+

License

The Rock Events is open-sourced software licensed under the MIT license.