# PHP Event Bindings

**URL:** https://forum.kirupa.com/t/php-event-bindings/271909
**Category:** open source
**Created:** [September 30, 2008, 9:54am UTC](https://forum.kirupa.com/t/php-event-bindings/271909 "2008-09-30T09:54:08Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![evildrummer](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/evildrummer/32/2308_2.png) [@evildrummer](https://forum.kirupa.com/u/evildrummer)
#### Post date: [September 30, 2008, 9:54am UTC](https://forum.kirupa.com/t/php-event-bindings/271909/1 "2008-09-30T09:54:08Z")

</div>

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/](http://github.com/stuartloxton/php-events/).

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

```php

<?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

// 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';
});

```
