concept-events.md 10.4 KB
Newer Older
1 2 3
Events
======

Qiang Xue committed
4 5 6 7
Events allow you to inject custom code into existing code at certain execution points. You can attach custom
code to an event so that when the event is triggered, the code gets executed automatically. For example,
a mailer object may trigger a `messageSent` event when it successfully sends out a message. If you want to keep
track of the messages that are successfully sent, you may attach the tracking code to the `messageSent` event.
8

Qiang Xue committed
9 10
Yii introduces a base class called [[yii\base\Component]] to support events. If a class needs to trigger
events, it should extend from [[yii\base\Component]] or its child class.
11

Alexander Makarov committed
12

13
<a name="triggering-events"></a>
Qiang Xue committed
14 15
Triggering Events
-----------------
Alexander Makarov committed
16

Qiang Xue committed
17 18
Events are triggered by calling the [[yii\base\Component::trigger()]] method. The method requires an *event name*
and optionally an event object which describes the parameters to be passed to the event handlers. For example,
Alexander Makarov committed
19

Qiang Xue committed
20 21
```php
namespace app\components;
Alexander Makarov committed
22

Qiang Xue committed
23 24
use yii\base\Component;
use yii\base\Event;
Alexander Makarov committed
25

Qiang Xue committed
26 27 28
class Foo extends Component
{
    const EVENT_HELLO = 'hello';
Alexander Makarov committed
29

Qiang Xue committed
30 31 32 33 34
    public function bar()
    {
        $this->trigger(self::EVENT_HELLO);
    }
}
Alexander Makarov committed
35
```
36

Qiang Xue committed
37 38 39 40 41 42
In the above code, when you call `bar()`, it will trigger an event named `hello`.

> Tip: It is recommended to use class constants to represent event names. In the above example, the constant
  `EVENT_HELLO` is used to represent `hello`. This has two benefits. First, it prevents typos and can get IDE
  auto-completion support. Second, you can tell what events are supported by a class by simply checking the constant
  declarations.
43

Qiang Xue committed
44 45 46 47 48
Sometimes when triggering an event, you may want to pass along some additional information to the event handlers.
For example, a mailer may want pass the message information to the handlers of the `messageSent` event so that the handlers
can know what messages are sent. To do so, you can provide an event object as the second parameter to
the [[yii\base\Component::trigger()]] method. The event object must be an instance of the [[yii\base\Event]] class
or its child class. For example,
49 50

```php
Qiang Xue committed
51
namespace app\components;
52

Qiang Xue committed
53 54
use yii\base\Component;
use yii\base\Event;
55

Qiang Xue committed
56 57 58 59
class MessageEvent extends Event
{
    public $message;
}
60

Qiang Xue committed
61 62 63 64 65 66 67 68 69 70 71 72 73
class Mailer extends Component
{
    const EVENT_MESSAGE_SENT = 'messageSent';

    public function send($message)
    {
        // ...sending $message...

        $event = new MessageEvent;
        $event->message = $message;
        $this->trigger(self::EVENT_MESSAGE_SENT, $event);
    }
}
74 75
```

Qiang Xue committed
76 77
When the [[yii\base\Component::trigger()]] method is called, it will call handlers that are attached to
the named event.
78

Alexander Makarov committed
79

80
<a name="event-handlers"></a>
Qiang Xue committed
81 82 83 84 85
Event Handlers
--------------

An event handler is a [PHP callback](http://www.php.net/manual/en/language.types.callable.php) that gets executed
when the event it is attached to is triggered. You can use one of the following callbacks:
Alexander Makarov committed
86

Qiang Xue committed
87 88 89 90
- a global PHP function specified in terms of a string, e.g., `'trim()'`;
- an object method specified in terms of an array of an object and a method name, e.g., `[$object, $method]`;
- a static class method specified in terms of an array of a class name and a method name, e.g., `[$class, $method]`;
- an anonymous function, e.g., `function ($event) { ... }`.
Alexander Makarov committed
91

Qiang Xue committed
92
The signature of an event handler is:
Alexander Makarov committed
93 94

```php
Qiang Xue committed
95 96 97
function ($event) {
    // $event is an object of yii\base\Event or its child class
}
Alexander Makarov committed
98
```
99

Qiang Xue committed
100
Through the `$event` parameter, an event handler may get the following information about an event:
101

Qiang Xue committed
102 103 104
- [[yii\base\Event::name|event name]]
- [[yii\base\Event::sender|event sender]]: the object whose `trigger()` method is called.
- [[yii\base\Event::data|custom data]]: the data that is provided when attaching the event handler (to be explained shortly).
Larry Ullman committed
105

Larry Ullman committed
106

107
<a name="attaching-event-handlers"></a>
Qiang Xue committed
108 109 110 111
Attaching Event Handlers
------------------------

You can attach a handler to an event by calling the [[yii\base\Component::on()]] method. For example,
Larry Ullman committed
112 113

```php
Qiang Xue committed
114 115 116 117
$foo = new Foo;

// the handler is a global function
$foo->on(Foo::EVENT_HELLO, 'function_name');
Larry Ullman committed
118

Qiang Xue committed
119 120
// the handler is an object method
$foo->on(Foo::EVENT_HELLO, [$object, 'methodName']);
Larry Ullman committed
121

Qiang Xue committed
122 123 124 125 126 127 128
// the handler is a static class method
$foo->on(Foo::EVENT_HELLO, ['app\components\Bar', 'methodName']);

// the handler is an anonymous function
$foo->on(Foo::EVENT_HELLO, function ($event) {
    // event handling logic
});
Larry Ullman committed
129 130
```

131 132 133 134
You may also attach event handlers through [configurations](concept-configurations.md). For more details, please
refer to the [Configurations](concept-configurations.md#configuration-format) chapter.


Qiang Xue committed
135 136
When attaching an event handler, you may provide additional data as the third parameter to [[yii\base\Component::on()]].
The data will be made available to the handler when the event is triggered and the handler is called. For example,
Larry Ullman committed
137 138

```php
Qiang Xue committed
139 140 141 142 143
// The following code will display "abc" when the event is triggered
// because $event->data contains the data passed to "on"
$foo->on(Foo::EVENT_HELLO, function ($event) {
    echo $event->data;
}, 'abc');
Larry Ullman committed
144 145
```

Qiang Xue committed
146 147 148 149
You may attach one or multiple handlers to a single event. When an event is triggered, the attached handlers
will be called in the order they are attached to the event. If a handler needs to stop the invocation of the
handlers behind it, it may set the [[yii\base\Event::handled]] property of the `$event` parameter to be true,
like the following,
150

Qiang Xue committed
151 152 153 154 155 156 157 158 159 160
```php
$foo->on(Foo::EVENT_HELLO, function ($event) {
    $event->handled = true;
});
```

By default, a newly attached handler is appended to the existing handler queue for the event.
As a result, the handler will be called in the last place when the event is triggered.
To insert the new handler at the start of the handler queue so that the handler gets called first, y
ou may call [[yii\base\Component::on()]] by passing the fourth parameter `$append` as false:
161 162

```php
Qiang Xue committed
163 164 165
$foo->on(Foo::EVENT_HELLO, function ($event) {
    // ...
}, $data, false);
166 167
```

Qiang Xue committed
168

169
<a name="detaching-event-handlers"></a>
Qiang Xue committed
170 171 172 173
Detaching Event Handlers
------------------------

To detach a handler from an event, call the [[yii\base\Component::off()]] method. For example,
174 175

```php
Qiang Xue committed
176 177 178 179 180 181 182 183 184 185 186
// the handler is a global function
$foo->off(Foo::EVENT_HELLO, 'function_name');

// the handler is an object method
$foo->off(Foo::EVENT_HELLO, [$object, 'methodName']);

// the handler is a static class method
$foo->off(Foo::EVENT_HELLO, ['app\components\Bar', 'methodName']);

// the handler is an anonymous function
$foo->off(Foo::EVENT_HELLO, $anonymousFunction);
187 188
```

Qiang Xue committed
189 190 191 192 193 194 195 196 197
Note that in general you should not try to detach an anonymous function unless you store it
somewhere when it is attached to the event. In the above example, we assume the anonymous
function is stored as a variable `$anonymousFunction`.

To detach ALL handlers from an event, simply call [[yii\base\Component::off()]] without the second parameter:

```php
$foo->off(Foo::EVENT_HELLO);
```
Larry Ullman committed
198

199

200
<a name="class-level-event-handlers"></a>
201 202
Class-Level Event Handlers
--------------------------
203

204 205 206 207
In the above sections, we have described how to attach a handler to an event at *instance level*.
Sometimes, you may want to respond to an event triggered by EVERY instance of a class instead of
a specific instance. Instead of attaching an event handler to every instance, you may attach the handler
at *class level* by calling the static method [[yii\base\Event::on()]].
Larry Ullman committed
208

209 210 211
For example, an [Active Record](db-active-record.md) object will trigger a [[yii\base\ActiveRecord::EVENT_AFTER_INSERT]]
event whenever it inserts a new record into the database. In order to track insertions done by EVERY
[Active Record](db-active-record.md) object, you may write the following code:
212 213

```php
214 215 216 217 218 219 220
use Yii;
use yii\base\Event;
use yii\db\ActiveRecord;

Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
    Yii::trace(get_class($event->sender) . ' is inserted');
});
221 222
```

223 224 225 226 227 228 229 230 231
The event handler will get invoked whenever an instance of [[yii\base\ActiveRecord|ActiveRecord]] or its child class triggers
the [[yii\base\ActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]] event. In the handler, you can get the object
that triggers the event through `$event->sender`.

When an object triggers an event, it will first call instance-level handlers, followed by class-level handlers.

You may trigger an *class-level* event by calling the static method [[yii\base\Event::trigger()]]. A class-level
event is not associated with a particular object. As a result, it will cause the invocation of class-level event
handlers only. For example,
232 233

```php
234 235 236 237 238 239 240
use yii\base\Event;

Event::on(Foo::className(), Foo::EVENT_HELLO, function ($event) {
    echo $event->sender;  // displays "app\models\Foo"
});

Event::trigger(Foo::className(), Foo::EVENT_HELLO);
241 242
```

243
Note that in this case, `$event->sender` refers to the name of the class triggering the event instead of an object instance.
Larry Ullman committed
244

245 246
> Note: Because a class-level handler will respond to an event triggered by any instance of that class or its child
  class, you should use it carefully, especially if the class is a low-level base class, such as [[yii\base\Object]].
247

248
To detach a class-level event handler, call [[yii\base\Event::off()]]. For example,
249 250

```php
251 252 253 254 255 256 257 258
// detach $handler
Event::off(Foo::className(), Foo::EVENT_HELLO, $handler);

// detach all handlers of Foo::EVENT_HELLO
Event::off(Foo::className(), Foo::EVENT_HELLO);
```


259
<a name="global-events"></a>
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
Global Events
-------------

The so-called *global event* is actually a trick based on the event mechanism described above.
It requires a globally accessible singleton, such as the [application](structure-applications.md) instance.

An event sender, instead of calling its own `trigger()` method, will call the singleton's `trigger()` method
to trigger the event. Similarly, the event handlers are attached to the event of the singleton. For example,

```php
use Yii;
use yii\base\Event;
use app\components\Foo;

Yii::$app->on('bar', function ($event) {
    echo get_class($event->sender);  // displays "app\components\Foo"
276
});
277 278

Yii::$app->trigger('bar', new Event(['sender' => new Foo]));
279 280
```

281 282 283 284 285 286
A benefit of global events is that you do not need the object when attaching a handler to the event
which will be triggered by the object. Instead, the handler attachment and the event triggering are both
done through the singleton (e.g. the application instance).

However, because the namespace of the global events is shared by all parties, you should name the global events
wisely, such as introducing some sort of namespace (e.g. "frontend.mail.sent", "backend.mail.sent").