Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@DHS
Created July 2, 2012 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DHS/3035023 to your computer and use it in GitHub Desktop.
Save DHS/3035023 to your computer and use it in GitHub Desktop.
Plugins in PHP
<?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