merged branch jalliot/event-subscriber (PR #2021)

Commits
-------

3223c5a Removed now useless test
21cf0ac Backported new behaviour from PR #2148 and removed check for interface at run-time
8b240d4 Implementation of kernel.event_subscriber tag for services.

Discussion
----------

Added missing kernel.event_subscriber tag (closes #2012)

This PR adds a ``kernel.event_subscriber`` tag which allows to register services as event subscribers in the same way ``kernel.event_listener`` allows to register them as event listeners.
The service is still lazy loaded and the DIC does not need to be recompiled for every modification in the service's code.

There is one important thing to remember:
If the service is created by a factory, the class parameter **MUST** reflect the real class of the service, although it is not needed at the moment for the DIC. For that issue, we could either forbid services created by factories or add a note to the documentation.

This PR closes #2012.

---------------------------------------------------------------------------

by jalliot at 2011/08/24 06:42:18 -0700

I'm not sure the test is good enough so feel free to add some more.

---------------------------------------------------------------------------

by jalliot at 2011/08/25 03:46:20 -0700

I re-implemented the check for EventSubscriberInterface in ContainerAwareEventDispatcher because I think the overhead is minimum and it allows to use this method even without the tag (at run-time).
I also added some tests for RegisterKernelListenersPass.

---------------------------------------------------------------------------

by stof at 2011/09/04 02:42:00 -0700

@jalliot Your branch conflicts with the current master. could you rebase it ?

---------------------------------------------------------------------------

by jalliot at 2011/09/04 02:57:03 -0700

Rebased

---------------------------------------------------------------------------

by jalliot at 2011/09/13 02:19:46 -0700

@fabpot What do you think about this PR? At the moment, the subscribers are not really usable in Symfony2 because of the lack of this tag.

---------------------------------------------------------------------------

by fabpot at 2011/09/13 04:17:46 -0700

I don't like subscribers. There are other PRs on adding more support for them, but the reality is that they are complex for no added benefit. I'm wondering if it wouldn't be better to just remove them altogether.

---------------------------------------------------------------------------

by jalliot at 2011/09/13 04:38:20 -0700

@fabpot Well I prefer listeners too but I think that if Symfony2 does support subscribers (which it does at the moment), it should do it properly and completely, thus allowing to register subscriber services like here or to register several methods for one same event like in #2148.
But I guess that if you merged those 2 PRs (well actually this one would have to be modified first if #2148 is merged but I'll do it then), many use cases would be covered and people should stop asking for more support :) (except maybe for removing the static modifier but this would be wrong IMO and prevent entirely this PR).

---------------------------------------------------------------------------

by fabpot at 2011/09/28 11:47:10 -0700

@jalliot: #2148 has been merged. Can you update this PR accordingly? thanks.

---------------------------------------------------------------------------

by jalliot at 2011/09/28 12:00:44 -0700

Sure thing. Will do it as well as removing the check for the interface tonight or tomorrow :)

---------------------------------------------------------------------------

by jalliot at 2011/09/29 08:53:17 -0700

@fabpot Check for interface removed and #2148 merged. Also rebased on latest master.

---------------------------------------------------------------------------

by fabpot at 2011/09/29 09:09:11 -0700

Tests do not pass.

---------------------------------------------------------------------------

by jalliot at 2011/09/29 09:18:48 -0700

@fabpot Fixed
This commit is contained in:
Fabien Potencier 2011-09-29 23:27:29 +02:00
commit b3ea939c35
4 changed files with 159 additions and 0 deletions

View File

@ -21,6 +21,7 @@ use Symfony\Component\EventDispatcher\Event;
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Bernhard Schussek <bernhard.schussek@symfony.com>
* @author Jordan Alliot <jordan.alliot@gmail.com>
*/
class ContainerAwareEventDispatcher extends EventDispatcher
{
@ -103,6 +104,27 @@ class ContainerAwareEventDispatcher extends EventDispatcher
return parent::getListeners($eventName);
}
/**
* Adds a service as event subscriber
*
* @param string $serviceId The service ID of the subscriber service
* @param string $class The service's class name (which must implement EventSubscriberInterface)
*/
public function addSubscriberService($serviceId, $class)
{
foreach ($class::getSubscribedEvents() as $eventName => $params) {
if (is_string($params)) {
$this->listenerIds[$eventName][] = array($serviceId, $params, 0);
} elseif (is_string($params[0])) {
$this->listenerIds[$eventName][] = array($serviceId, $params[0], $params[1]);
} else {
foreach ($params as $listener) {
$this->listenerIds[$eventName][] = array($serviceId, $listener[0], isset($listener[1]) ? $listener[1] : 0);
}
}
}
}
/**
* {@inheritDoc}
*

View File

@ -43,5 +43,18 @@ class RegisterKernelListenersPass implements CompilerPassInterface
$definition->addMethodCall('addListenerService', array($event['event'], array($id, $event['method']), $priority));
}
}
foreach ($container->findTaggedServiceIds('kernel.event_subscriber') as $id => $attributes) {
// We must assume that the class value has been correcly filled, even if the service is created by a factory
$class = $container->getDefinition($id)->getClass();
$refClass = new \ReflectionClass($class);
$interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';
if (!$refClass->implementsInterface($interface)) {
throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface));
}
$definition->addMethodCall('addSubscriberService', array($id, $class));
}
}
}

View File

@ -14,6 +14,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Bundle\FrameworkBundle\ContainerAwareEventDispatcher;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\DependencyInjection\Scope;
class ContainerAwareEventDispatcherTest extends \PHPUnit_Framework_TestCase
@ -39,6 +40,27 @@ class ContainerAwareEventDispatcherTest extends \PHPUnit_Framework_TestCase
$dispatcher->dispatch('onEvent', $event);
}
public function testAddASubscriberService()
{
$event = new Event();
$service = $this->getMock('Symfony\Bundle\FrameworkBundle\Tests\SubscriberService');
$service
->expects($this->once())
->method('onEvent')
->with($event)
;
$container = new Container();
$container->set('service.subscriber', $service);
$dispatcher = new ContainerAwareEventDispatcher($container);
$dispatcher->addSubscriberService('service.subscriber', 'Symfony\Bundle\FrameworkBundle\Tests\SubscriberService');
$dispatcher->dispatch('onEvent', $event);
}
public function testPreventDuplicateListenerService()
{
$event = new Event();
@ -174,3 +196,16 @@ class Service
{
}
}
class SubscriberService implements EventSubscriberInterface
{
static function getSubscribedEvents() {
return array(
'onEvent' => 'onEvent',
);
}
function onEvent(Event $e)
{
}
}

View File

@ -0,0 +1,89 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\RegisterKernelListenersPass;
class RegisterKernelListenersPassTest extends \PHPUnit_Framework_TestCase
{
/**
* Tests that event subscribers not implementing EventSubscriberInterface
* trigger an exception.
*
* @expectedException \InvalidArgumentException
*/
public function testEventSubscriberWithoutInterface()
{
// one service, not implementing any interface
$services = array(
'my_event_subscriber' => array(0 => array()),
);
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('stdClass'));
$builder = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.event_listener here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->onConsecutiveCalls(array(), $services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->returnValue($definition));
$registerListenersPass = new RegisterKernelListenersPass();
$registerListenersPass->process($builder);
}
public function testValidEventSubscriber()
{
$services = array(
'my_event_subscriber' => array(0 => array()),
);
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\SubscriberService'));
$builder = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.event_listener here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->onConsecutiveCalls(array(), $services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->returnValue($definition));
$registerListenersPass = new RegisterKernelListenersPass();
$registerListenersPass->process($builder);
}
}
class SubscriberService implements \Symfony\Component\EventDispatcher\EventSubscriberInterface
{
static function getSubscribedEvents() {}
}