Last active
August 29, 2015 13:56
-
-
Save meadsteve/9274260 to your computer and use it in GitHub Desktop.
Symfony events without statics
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 | |
namespace MeadSteve\Eventing; | |
require_once "vendor/autoload.php"; | |
use Symfony\Component\EventDispatcher\EventDispatcher as SymfonyEventDispatcher; | |
use Symfony\Component\EventDispatcher\EventDispatcherInterface; | |
use \Symfony\Component\EventDispatcher\Event; | |
interface ObjectListenerInterface | |
{ | |
public function addListeners(EventDispatcherInterface $dispatcher); | |
public function removeListeners(EventDispatcherInterface $dispatcher); | |
} | |
class EventDispatcher extends SymfonyEventDispatcher | |
{ | |
public function addObjectListener(ObjectListenerInterface $subscriber) | |
{ | |
$subscriber->addListeners($this); | |
} | |
public function removeObjectListener(ObjectListenerInterface $subscriber) | |
{ | |
$subscriber->removeListeners($this); | |
} | |
} | |
class MessageEvent extends Event | |
{ | |
protected $message; | |
public function __construct($message) | |
{ | |
$this->message = $message; | |
} | |
public function getMessage() | |
{ | |
return $this->message; | |
} | |
} | |
class Subscriber implements ObjectListenerInterface | |
{ | |
public function addListeners(EventDispatcherInterface $dispatcher) | |
{ | |
$dispatcher->addListener("say.message", array($this, "say")); | |
} | |
public function removeListeners(EventDispatcherInterface $dispatcher) | |
{ | |
$dispatcher->removeListener("say.message", array($this, "say")); | |
} | |
public function say(Event $event) | |
{ | |
if ($event instanceof MessageEvent) { | |
echo $event->getMessage(); | |
} | |
} | |
} | |
$dispatcher = new EventDispatcher(); | |
$subscriber = new Subscriber(); | |
$dispatcher->addObjectListener($subscriber); | |
$dispatcher->dispatch("say.message", new MessageEvent("hello")); | |
$dispatcher->removeObjectListener($subscriber); | |
$dispatcher->dispatch("say.message", new MessageEvent("I should not be said by subscriber")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment