PHP: How to implement an event handler?

I want to add a custom event handler to an object method.

I have a class with a method.

class Post {

    public function Add($title) {

        // beforeAdd event should be called here

        echo 'Post "' . $title . '" added.';
        return;
    }
}

I want to add an event to the method Addand pass the arguments of the method to the event handler method.

function AddEventHandler($event, $handler){
    // What should this function do?
}

$handler = function($title){
    return strtoupper($title);
}

AddEventHandler('beforeAdd', $handler);

Is it possible to do something like this? Hope my question is clear.

+5
source share
4 answers

It should be pretty easy to use the functions defined here http://www.php.net/manual/en/book.funchand.php

In particular, you must save an array of handlers (or an array of arrays if you want to use multiple handlers for the same event), and then just do something like

function AddEventHandler($event, $handler){
    $handlerArray[$event] = $handler;
}

or

function AddEventHandler($event, $handler){
    $handlerArray[$event][] = $handler;
}

.

call_user_func" ( , )

+3

, < php 5.3, , create_function();

$handler = create_function('$title', 'return strtoupper($title);');

$ , .

+1

, ircmaxell .

ToroHook ToroPHP (Routing lib).

Hook

class ToroHook {
    private static $instance;
    private $hooks = array();

    private function __construct() {}
    private function __clone() {}

    public static function add($hook_name, $fn){
        $instance = self::get_instance();
        $instance->hooks[$hook_name][] = $fn;
    }

    public static function fire($hook_name, $params = null){
        $instance = self::get_instance();
        if (isset($instance->hooks[$hook_name])) {
            foreach ($instance->hooks[$hook_name] as $fn) {
                call_user_func_array($fn, array(&$params));
            }
        }
    }
    public static function remove($hook_name){
        $instance = self::get_instance();
        unset($instance->hooks[$hook_name]);
        var_dump($instance->hooks);
    }
    public static function get_instance(){
        if (empty(self::$instance)) {
            self::$instance = new Hook();
        }
        return self::$instance;
    }
}

hook

:

ToroHook::add('404', function($errorpage){
    render("page/not_found", array("errorpage" => $errorpage));
});
+1

sphido/events:

  • ( )
  • PHP-
  • .
  • /
  • add default handler

Event Handler Example

on('event', function () {
  echo "wow it works yeah!";
});

fire('event'); // print wow it works yeah!

Filter Function Example

add_filter('price', function($price) {
  return (int)$price . ' USD';
});

echo filter('price', 100); // print 100 USD
+1
source

All Articles