Skip to content

Instantly share code, notes, and snippets.

@meadsteve
Last active August 29, 2015 13:56
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 meadsteve/9274260 to your computer and use it in GitHub Desktop.
Save meadsteve/9274260 to your computer and use it in GitHub Desktop.
Symfony events without statics
<?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