ContainerAwareEventDispatcher.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bundle\FrameworkBundle;
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. use Symfony\Component\EventDispatcher\EventDispatcher;
  13. use Symfony\Component\EventDispatcher\Event;
  14. /**
  15. * Lazily loads listeners and subscribers from the dependency injection
  16. * container
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. * @author Bernhard Schussek <bernhard.schussek@symfony.com>
  20. */
  21. class ContainerAwareEventDispatcher extends EventDispatcher
  22. {
  23. /**
  24. * The container from where services are loaded
  25. * @var ContainerInterface
  26. */
  27. private $container;
  28. /**
  29. * The service IDs of the event listeners and subscribers
  30. * @var array
  31. */
  32. private $listenerIds;
  33. /**
  34. * Constructor.
  35. *
  36. * @param ContainerInterface $container A ContainerInterface instance
  37. */
  38. public function __construct(ContainerInterface $container)
  39. {
  40. $this->container = $container;
  41. }
  42. /**
  43. * Adds a service as event listener
  44. *
  45. * @param string|array $events One or more events for which the listener
  46. * is added
  47. * @param string $serviceId The ID of the listener service
  48. * @param integer $priority The higher this value, the earlier an event
  49. * listener will be triggered in the chain.
  50. * Defaults to 0.
  51. */
  52. public function addListenerService($events, $serviceId, $priority = 0)
  53. {
  54. if (!is_string($serviceId)) {
  55. throw new \InvalidArgumentException('Expected a string argument');
  56. }
  57. foreach ((array)$events as $event) {
  58. // Prevent duplicate entries
  59. $this->listenerIds[$event][$serviceId] = $priority;
  60. }
  61. }
  62. /**
  63. * {@inheritDoc}
  64. *
  65. * Lazily loads listeners for this event from the dependency injection
  66. * container.
  67. */
  68. public function dispatch($eventName, Event $event = null)
  69. {
  70. if (isset($this->listenerIds[$eventName])) {
  71. foreach ($this->listenerIds[$eventName] as $serviceId => $priority) {
  72. $this->addListener($eventName, $this->container->get($serviceId), $priority);
  73. }
  74. }
  75. parent::dispatch($eventName, $event);
  76. }
  77. }