Why we should use Events?

[color="#333333"]Hi everyone,[/color]

[color="#333333"]I have a question about Events concept. Why we should use Events while we can override methods like afterSave() or afterDelete() .[/color]

[color="#333333"]Or when we should use Events? if you may describe more to me about this concept in Yii2.[/color]

in short,

it is concept of notifications.

one class is observable/invokable (which makes event available), other class(es) is consumer/sender which attaches/subscribes to event.

yii implements observer (class that manages connections between observable and consumers and notifies every class that was attached to particular event, sort of queue).

sometimes one class needs(or acts as a bonus) to notify another class(es) about some action or its stage of execution. it gives ability to your consumer class be able to attach to that event and possibly do extra stuff (logging, email… etc). or even interupt execution or change content (but debuging this becomes difficult).

So events may save you huge amount of time to inject some functionality very fast, but you may encounter huge problem with debugging if overuse events.

i didn’t dig deep into yii2, but it looks like it has 2 types of events: global (very risky) and per instance. Role of observer is done by Event class, as far as i understand.

here’s more valid info https://github.com/yiisoft/yii2/blob/master/docs/guide/concept-events.md


1 Like