Skip to content

Instantly share code, notes, and snippets.

@tbreuss
Created August 25, 2014 15:57
Show Gist options
  • Save tbreuss/1469774b8de9ca68f8f9 to your computer and use it in GitHub Desktop.
Save tbreuss/1469774b8de9ca68f8f9 to your computer and use it in GitHub Desktop.
A very simple example using the Symfony EventDispatcher component.
<?php
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MyListener
{
public function onFooAction(Event $event)
{
echo __CLASS__ . '/' . __METHOD__;
echo "<br>";
}
}
class MySubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
'foo.action' => ['onFooAction', 0],
'bar.action' => ['onBarAction', 0],
'baz.action' => ['onBazAction', 0]
];
}
public function onFooAction()
{
echo __CLASS__ . '/' . __METHOD__;
echo "<br>";
}
public function onBarAction()
{
echo __CLASS__ . '/' . __METHOD__;
echo "<br>";
}
public function onBazAction()
{
echo __CLASS__ . '/' . __METHOD__;
echo "<br>";
}
}
$dispatcher = new EventDispatcher();
$listener = new MyListener();
$dispatcher->addListener('foo.action', array($listener, 'onFooAction'));
$subscriber = new MySubscriber();
$dispatcher->addSubscriber($subscriber);
$dispatcher->addListener('baz.action', array($listener, 'onFooAction'));
$dispatcher->addListener('foo.action', function() {
echo __FUNCTION__;
echo "<br>";
});
echo "<h2>START</h2>";
echo "<h4>FOO-ACTION</h4>";
$dispatcher->dispatch('foo.action');
echo "<h4>BAR-ACTION</h4>";
$dispatcher->dispatch('bar.action');
echo "<h4>BAZ-ACTION</h4>";
$dispatcher->dispatch('baz.action');
echo "<h2>END</h2>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment