views:

33

answers:

2

I want to add custom event handler to object's method.

I've got a class with 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 method Add and pass method's argument(s) to the event handler.

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.

+2  A: 

Should be pretty easy using the functions defined here http://www.php.net/manual/en/book.funchand.php

In particular you should keep an handler array (or array of arrays if you want 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;
}

in case of multiple handlers.

Invoking the handlers then would be just matter of calling "call_user_func" (eventually in a cycle if multiple handlers are needed)

Michele Balistreri
@Michele how to call handler(s) from my `Add` method?
SaltLake
+1  A: 

Well, if you are using < php 5.3 then you cannot create a closure in such a way, but you can come close with create_function(); This would be

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

Then you store $handler in the class and you can call it as you desire.

tandu
PHP version is not an issue.
SaltLake