EventManagerAwareTrait.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. */
  9. namespace Zend\EventManager;
  10. use Traversable;
  11. /**
  12. * A trait for objects that provide events.
  13. *
  14. * If you use this trait in an object, you will probably want to also implement
  15. * EventManagerAwareInterface, which will make it so the default initializer in
  16. * a ZF2 MVC application will automatically inject an instance of the
  17. * EventManager into your object when it is pulled from the ServiceManager.
  18. *
  19. * @see Zend\Mvc\Service\ServiceManagerConfig
  20. */
  21. trait EventManagerAwareTrait
  22. {
  23. /**
  24. * @var EventManagerInterface
  25. */
  26. protected $events;
  27. /**
  28. * Set the event manager instance used by this context.
  29. *
  30. * For convenience, this method will also set the class name / LSB name as
  31. * identifiers, in addition to any string or array of strings set to the
  32. * $this->eventIdentifier property.
  33. *
  34. * @param EventManagerInterface $events
  35. * @return mixed
  36. */
  37. public function setEventManager(EventManagerInterface $events)
  38. {
  39. $identifiers = [__CLASS__, get_class($this)];
  40. if (isset($this->eventIdentifier)) {
  41. if ((is_string($this->eventIdentifier))
  42. || (is_array($this->eventIdentifier))
  43. || ($this->eventIdentifier instanceof Traversable)
  44. ) {
  45. $identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier));
  46. } elseif (is_object($this->eventIdentifier)) {
  47. $identifiers[] = $this->eventIdentifier;
  48. }
  49. // silently ignore invalid eventIdentifier types
  50. }
  51. $events->setIdentifiers($identifiers);
  52. $this->events = $events;
  53. if (method_exists($this, 'attachDefaultListeners')) {
  54. $this->attachDefaultListeners();
  55. }
  56. return $this;
  57. }
  58. /**
  59. * Retrieve the event manager
  60. *
  61. * Lazy-loads an EventManager instance if none registered.
  62. *
  63. * @return EventManagerInterface
  64. */
  65. public function getEventManager()
  66. {
  67. if (!$this->events instanceof EventManagerInterface) {
  68. $this->setEventManager(new EventManager());
  69. }
  70. return $this->events;
  71. }
  72. }