events.md 4.3 KB
Newer Older
1 2 3
Events
======

Larry Ullman committed
4 5
Yii uses events to "inject" custom code into existing code at certain execution points. For example, a comment object can trigger
an "add" event when the user adds a comment to a post. 
6

Larry Ullman committed
7
Events are very useful for two reasons. First, they can make your components more flexible. Second, you can hook your own code into the regular workflow of both the framework and the extensions in use.
8

Alexander Makarov committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Attaching event handlers
------------------------

One or multiple PHP callbacks, called *event handlers*, can be attached to an event. When an event is raised, the event
handlers will be invoked automatically in the order they were attached.

There are two main methods of attaching event handlers. It can be done either via code or via application config.

> Tip: In order to get up to date list of framework and extension events search code for `->trigger`.

### Attaching event handlers via code

You can assign event handlers using `on` method of the component instance. The method's first argument is the name of
the event to watch for; the second is the handler to be called when that event occurs:

```php
$component->on($eventName, $handler);
```
27 28 29

The handler must be a valid PHP callback. This could be represented as:

Alexander Makarov committed
30 31 32 33
- The name of a global function.
- An array consisting of a model name and method name.
- An array consisting of an object and a method name.
- An anonymous function.
34 35 36 37 38 39 40 41 42 43 44 45

```php
// Global function:
$component->on($eventName, 'functionName');

// Model and method names:
$component->on($eventName, ['Modelname', 'functionName']);

// Object and method name:
$component->on($eventName, [$obj, 'functionName']);

// Anonymous function:
Alexander Makarov committed
46
$component->on($eventName, function ($event) {
47
    // Use $event.
48 49 50
});
```

51
As shown in the anonymous function example, the event handling function must be defined so that it takes one argument.
52
This will be an [[yii\base\Event]] object.
53

Alexander Makarov committed
54 55 56 57
In order to pass extra data supply it via third argument:

```php
$component->on($eventName, function ($event) {
58
    // the extra data can be accessed via $event->data
Alexander Makarov committed
59 60 61 62 63 64 65 66 67
}, $extraData);
```

### Attaching event handlers via config

It is possible to use application config to attach event hanelers:

```php
return [
68 69 70 71 72 73 74 75 76
    // ...
    'components' => [
        'db' => [
            // ...
            'on afterOpen' => function ($event) {
                // do something right after connected to database
            }
        ],
    ],
Alexander Makarov committed
77 78
];
```
79

Larry Ullman committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
Triggering events
-----------------

Any component can trigger an event using the `trigger` method:

```php
$this->trigger('myEvent');

// or

$event = new CreateUserEvent(); // extended from yii\base\Event
$event->userName = 'Alexander';
$this->trigger('createUserEvent', $event);
```

Event name should be unique within the class it is defined at. Event names are *case-sensitive*. It is a good practice
to define event names using class constants:

```php
class Mailer extends Component
{
    const EVENT_SEND_EMAIL = 'sendEmail';

    public function send()
    {
        // ...
        $this->trigger(self::EVENT_SEND_EMAIL);
    }
}
```

111 112 113 114 115 116
Removing Event Handlers
-----------------------

The correspondoing `off` method removes an event handler:

```php
117
$component->off($eventName);
118 119
```

Alexander Makarov committed
120 121
Yii supports the ability to associate multiple handlers with the same event. When using `off` as in the above,
every handler is removed. To remove only a specific handler, provide that as the second argument to `off`:
122 123

```php
124
$component->off($eventName, $handler);
125 126
```

127 128 129 130 131
The `$handler` should be presented in the `off` method in the same way as was presented in `on` in order to remove it.

Global Events
-------------

Alexander Makarov committed
132 133
You can use "global" events instead of per-component ones. To trigger a global event use an application instance instead
of specific component:
134 135

```php
Alexander Makarov committed
136
Yii::$app->trigger($eventName);
137 138
```

Alexander Makarov committed
139
In order to attach a handler to it use the following:
140 141

```php
Alexander Makarov committed
142
Yii::$app->on($eventName, $handler);
143 144
```

145 146 147
Class Events
------------

Alexander Makarov committed
148 149
It is possible to attach event handlers to all instances of a class instead of individual instances. To do so, use
the static `Event::on` method:
150 151 152

```php
Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
153
    Yii::trace(get_class($event->sender) . ' is inserted.');
154 155 156 157
});
```

The code above defines a handler that will be triggered for every Active Record object's `EVENT_AFTER_INSERT` event.