Home Account

simple event dispatcher php

2011-12-29 17:48 dennis iversen

Tags: php scripts-and-functions

There is a couple of event dispatchers written in PHP.

But you could be build something more simple (primitive someone might say) like this:


    function triggerEvent ($methods, $args = null) {
        if (!is_array($methods)) return;
        $str = '';
        foreach ($methods as $key => $val) {
            $ary = explode('::', $val);
            $module = $class = $ary[0];
            $method = $ary[1];

            // include class $module, e.g. accountverify.inc
            include ($module . ".inc");

            // call class with specified method and collect output
            // in a string and do other things. e.g. send an email. 
            $str.= $class::$method($args);
        }
        return $str;
    }

Now in your account system you could implement something like this, e.g. on account::signup()

triggerEvent(array('accountverify::verify'), $res); 

were $res is the boolean operation telling if verification is correct or not. Now you can send and email to an administrator or something similar in your accountverify::verify method. And at the same time you would be able to add more methods when users are signing up.

In order to make this even smarter you might add the called methods in a configuration file, so that you could specify classes and methods to call in a configuration file.

This page has been requested 4254 times