Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juneym/bb0e9241343d2d4b2d08 to your computer and use it in GitHub Desktop.
Save juneym/bb0e9241343d2d4b2d08 to your computer and use it in GitHub Desktop.
Event manager based on observer pattern, from this article http://www.cainsvault.com/design-pattern-php-event-dispatcher/
<?php
interface SubscriberInterface {
public static function getSubscribedEvents();
}
class BlogSubscriber implements SubscriberInterface {
public static function getSubscribedEvents() {
return array(
'blog_update' => 'Listener'
);
}
// The subscribed function
public function Listener(BlogPublisher $pub) {
// Write to log
// $pub->getTitle();
}
}
// We also need to extend the event manager to
// deal with subscribed interfaces.
class EventManager {
private $listeners = array();
public function listen($event, $callback) {
$this->listeners[$event][] = $callback;
}
public function dispatch($event, PublisherInterface $param) {
foreach ($this->listeners[$event] as $listener) {
call_user_func_array($listener, array($param));
}
}
public function addSubscriber(SubscriberInterface $sub) {
$listeners = $sub->getSubscribedEvents();
foreach ($listeners as $event => $listener) {
// Add the subscribed function as an event
$this->listen($event, array($sub, $listener));
}
}
}
// How it works
$event = new EventManager();
// Create the blog updater
$blog = new BlogPublisher($event);
// Register a subscriber, can be anything
$subscriber = new BlogSubscriber();
// Add the subscriber
$event->addSubscriber($subscriber);
// Update the blog
$blog->updateBlog();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment