Following from a similar post, where I packaged up my standard web services libraries to avoid repeating myself, I decided to do the same for Events and triggers.

Events provide a very powerful, flexible and simple way of providing hooks for other code to attach to, in a loosely coupled way. I’ve been using event driven development in my PHP code for years, way back since the first days of Elgg. In Elgg, events and triggers proved to be one of the frameworks most powerful, and a major factor in its success, allowing plugin developers to easily change core functionality without changing a line of core code.

Anyway, I’ve used Events in one form or another in pretty much every framework since, and I’ve found myself increasingly cutting and pasting code around, so I figured it’d be sensible to package this up into a reusable library as well. Although it is designed to be simple, the library is pretty powerful.

One particularly useful feature is that event listeners can include regexp!

Triggering an event…

If you were writing a framework that had users for example, and you wanted to allow plugin authors to hook in and do something when a new user is created, you might do something like this in your registration code…

function registerUser($username, $password) {

    ...
    // User creation code here
    ...

    // Ok, now tell everyone that a user has been created
    \simple_event_dispatcher\Events::trigger('user', 'create', ['user' => $new_user]);

}

Listening to an event…

So, if you wanted to listen to the user creation event inside your plugin…

// Register an event for every time a user is created
\simple_event_dispatcher\Events::register('user', 'create', function($namespace, $event, &$parameters) { 

    // Your code here

});

You can replace any part of the $namespace or $event string in Events::register (‘user‘ and ‘create‘ respectively in the example above) with regular expression. So, you could, for example, replace ‘user‘ with ‘*‘ to listen with any create event.

Code on GitHub, have fun!

» Visit the project on Github...

4 thoughts on “Simple PHP Event Dispatcher framework

  1. So, another in a series of posts where I package up some code I often use into a reusable library, let me introduce a simple PHP library for creating virtual pages.
    Virtual pages are pages on a website that are generated in code, and are sent to the client’s browser, but don’t correspond directly to a physical file. This process requires mod_rewrite on Apache, but similar functionality exists in other web servers.
    Defining your endpoint
    You must specify your endpoint, and then a handling function. This function can be anything callable; functions, methods or an enclosure.



    simple_page_handlerPage::create(‘my/page/’, function($page, array $subpages) {
    // Your page handling code
    });


    123

    simple_page_handlerPage::create(‘my/page/’, function($page, array $subpages) {        // Your page handling code});


    Writing your endpoint handler
    You then trigger the handled pages by writing a page handler, and then directing Apache to redirect unhandled requests to this endpoint.
    Example endpoint:



    try {
    if (!simple_page_handlerPage::call(simple_page_handlerInput::get(‘page’))) {
    simple_page_handlerPage::set503();
    echo “Something went wrong.”;
    }
    } catch (Exception $e) {
    echo $e->getMessage();
    }


    12345678

    try {        if (!simple_page_handlerPage::call(simple_page_handlerInput::get(‘page’))) {            simple_page_handlerPage::set503();            echo “Something went wrong.”;        }} catch (Exception $e) {    echo $e->getMessage();}


    And your redirect code:



    # Redirect anything that isn’t a real file to our example page handler
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ example_page_handler.php?page=$1 [QSA]


    12345

    # Redirect anything that isn’t a real file to our example page handlerRewriteEngine onRewriteCond %{REQUEST_FILENAME} !dRewriteCond %{REQUEST_FILENAME} !f RewriteRule ^(.*)$ example_page_handler.php?page=$1 [QSA]


    Hopefully this’ll be useful to someone!
    » Visit the project on Github…

    Thanks for visiting! If you’re new here you might like to read a bit about me. You may also like to follow me on Twitter!

    (Psst… I am also available to hire! Find out more…)
    Share this:EmailLinkedInTwitterGoogleFacebookReddit

  2. Here is the latest in a series of libraries I’ve been releasing which package up some of my often used, cut and pasted code, into reusable modules for myself and others to use.
    So here is the companion piece to my previously released Web Services client library, a web services API endpoint library.
    Usage
    The library allows you to expose a Callable type (function, object method or static function, closure, and call it via a built in Simple Page Handler endpoint that you can attach to a virtual page (e.g. http://example.com/api).
    The library will then use reflection to extract the required and optional parameters, and any default values to pass, and then pass them accordingly.
    Once the code has run it’ll trigger an event which you should listen to and determine what format to output the results in based on the 'format' parameter. You might want to look at the Simple Template Library to help you here!
    I’ve written an example handler that exposes a single API, but feel free to fire over any comments or questions!
    » Visit the project on Github…
    Share this:EmailLinkedInTwitterGoogleFacebookReddit

Leave a Reply