PHP Event Bindings

So now that PHP 5.3 supports event binding I thought I would play about with creating a PHP event binding system. The syntax is similar to jQuery. Source hosted at http://github.com/stuartloxton/php-events/.

[SIZE=“3”]Example[/SIZE]


<?php
	include('index.php');

	class database extends EventHandler {
		
		function connect() {
			// Do connection code
			$this->connected();
		}
		
		function query() {
			// make code;
			$success = true;
			if($success) {
				$this->querySuccess(array('test', 'woop', 'success'));
			} else {
				$this->queryError();
			}
		}
		
	}
	
	$db = new database;
	
	$db->connected(function() {
		define('DB_CONNECTED', 'true');
		echo '<h1>Connected</h1>';
		return Event::unbind();
	});
	$db->querySuccess(function($e) {
		echo '<h1>Query Returned</h1><pre>';
		return Event::stop();
		echo '</pre>';
	});
	$db->queryError(function() {
		header('Location: /error/oops/');
		exit;
	});
	$db->connect();
	$db->query();
	$db->connect();
?>

This would firstly create the class database to have event handling functions. It then binds a function to run on connected status. A function for query Success and query Failure.

When the Database is connected the connect functions are triggered. however one thing to point out is that in the binded function for connect it returns Event::unbind() which then unbinds it from the event so isn’t run the second time the DB is connected.

I’m still doing a lot of work on it but thought I would post it here to see what you guys thought.

It only runs on PHP5.3 and above, otherwise the syntax would look like this:


// PHP < 5.3
$class->event(create_function('$e', 'define("SOMETHING", "10"); echo "something";'));
// PHP >= 5.3
$class->event(function($e) {
    define('SOMETHING', '10');
    echo 'something';
});