Created
January 17, 2014 12:06
-
-
Save nunomazer/8472389 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/
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 | |
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