1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Webino™ (http://webino.sk) |
4
|
|
|
* |
5
|
|
|
* @link https://github.com/webino for the canonical source repository |
6
|
|
|
* @copyright Copyright (c) 2015-2017 Webino, s.r.o. (http://webino.sk) |
7
|
|
|
* @author Peter Bačinský <[email protected]> |
8
|
|
|
* @license BSD-3-Clause |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace WebinoEventLib; |
12
|
|
|
|
13
|
|
|
use Traversable; |
14
|
|
|
use Zend\EventManager\EventManagerInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Class EventsAwareTrait |
18
|
|
|
*/ |
19
|
|
|
trait EventsAwareTrait |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var EventManagerInterface |
23
|
|
|
*/ |
24
|
|
|
protected $events; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Set the event manager instance used by this context. |
28
|
|
|
* |
29
|
|
|
* For convenience, this method will also set the class name / LSB name as |
30
|
|
|
* identifiers, in addition to any string or array of strings set to the |
31
|
|
|
* $this->eventIdentifier property. |
32
|
|
|
* |
33
|
|
|
* @param EventManagerInterface $events |
34
|
|
|
* @return mixed |
35
|
|
|
*/ |
36
|
|
|
public function setEvents(EventManagerInterface $events) |
37
|
|
|
{ |
38
|
|
|
$identifiers = [__CLASS__, get_class($this)]; |
39
|
|
|
if (isset($this->eventIdentifier)) { |
40
|
|
|
if ((is_string($this->eventIdentifier)) |
41
|
|
|
|| (is_array($this->eventIdentifier)) |
42
|
|
|
|| ($this->eventIdentifier instanceof Traversable) |
43
|
|
|
) { |
44
|
|
|
$identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier)); |
45
|
|
|
} elseif (is_object($this->eventIdentifier)) { |
|
|
|
|
46
|
|
|
$identifiers[] = $this->eventIdentifier; |
47
|
|
|
} |
48
|
|
|
// silently ignore invalid eventIdentifier types |
49
|
|
|
} |
50
|
|
|
$events->setIdentifiers($identifiers); |
51
|
|
|
$this->events = $events; |
52
|
|
|
if (method_exists($this, 'attachDefaultListeners')) { |
53
|
|
|
$this->attachDefaultListeners(); |
|
|
|
|
54
|
|
|
} |
55
|
|
|
return $this; |
56
|
|
|
} |
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 getEvents() |
66
|
|
|
{ |
67
|
|
|
if (!$this->events instanceof EventManagerInterface) { |
68
|
|
|
$this->setEvents(new EventManager); |
69
|
|
|
} |
70
|
|
|
return $this->events; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: