Created
July 2, 2012 19:08
-
-
Save DHS/3035023 to your computer and use it in GitHub Desktop.
Plugins in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Plugins in PHP | |
* | |
* First read this: | |
* http://blog.ircmaxell.com/2012/03/handling-plugins-in-php.html | |
* | |
* The 'mediator' pattern is described as the most ubiquitous so I | |
* took that, fleshed it out a little, made it compatible with | |
* PHP 5.2 and added some error messages. | |
* | |
* This will likely be the basis for the plugin architecture in Rat: | |
* https://github.com/DHS/rat | |
* | |
* Feedback welcome! | |
* | |
*/ | |
class Event { | |
protected $events = array(); | |
public function attach($eventName, $callback) { | |
if ( ! isset($this->events[$eventName])) { | |
$this->events[$eventName] = array(); | |
} | |
$this->events[$eventName][] = $callback; | |
} | |
public function trigger($eventName, $data = null) { | |
if (isset($this->events[$eventName])) { | |
foreach ($this->events[$eventName] as $callback) { | |
if (function_exists($callback)) { | |
$callback($data, $eventName); | |
} else { | |
echo "<p>Function '$callback' not found, called by '$eventName' event.</p>"; | |
} | |
} | |
} else { | |
echo "<p>No functions bound to '$eventName' event.</p>"; | |
} | |
} | |
} | |
$event = new Event; | |
// Define a basic function | |
function say_hello($name) { | |
echo "<p>Hello $name!</p>"; | |
} | |
// Define another function | |
function say_hello_from($name, $eventName) { | |
echo "<p>Hello $name from the '$eventName' event.</p>"; | |
} | |
// Attach a function to first event | |
$event->attach('first', 'say_hello'); | |
// Attach another function to first event | |
$event->attach('first', 'say_hello_from'); | |
// Attach a non-existent function to first event | |
$event->attach('first', 'non_existent_function'); | |
// Attach a function to a second event | |
$event->attach('second', 'say_hello_from'); | |
// Trigger first event | |
$event->trigger('first', 'world'); | |
// Output: | |
// Hello world! | |
// Hello world from the 'first' event. | |
// Function 'non_existent_function' not found, called by 'first' event. | |
// Trigger second event | |
$event->trigger('second'); | |
// Output: | |
// Hello from the 'second' event. | |
// Trigger third event | |
$event->trigger('third'); | |
// Output: | |
// No functions bound to 'third' event. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment