Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real world example of Events in Yii2 [duplicate]

Tags:

php

yii

yii2

I learn about events from yii2 doc.

I know how it works, but i don't know where to use it and how to use it in my development.There is example of send email notification but i want a solid example which clear the idea where to use and how to use it .

MY code is below in model i write

const EVENT_NEW_USER = 'new-user';
public function sendMailto($event){
    $this->sendMail(arguments);
   // you code 
}  

in controller:

use yii\base\Component;
use yii\base\Event;

public function someaction (){
    $model->on(SignUpForm::EVENT_NEW_USER, [$model,'sendMailto'],['auth'=>$model_auth,'user_details'=>$user_details]);
    $model->trigger(SignUpForm::EVENT_NEW_USER); 
}
like image 986
Amitesh Kumar Avatar asked Oct 23 '15 05:10

Amitesh Kumar


1 Answers

I use events in Yii for loosely coupling sender and receiver of messages inside a single Yii installation (no distrubution, single server).

In my Yii software there are Yii modules for feature blocks. Customers get module sets depending on their feature requirements. These module need to commuicate with each other.

Example:

  • In Module 1 (sender module) there is a status update that needs to be communicated to users.
  • Module 2 (receiver module) sends status updates to twitter.
  • Module 3 (receiver module) send status updates via email.

In order to make sender modules independend of receiver modules, i use the Yii event mechanisms. So, Module 1 does not need to know anything about the receiver and Modules 2 and 3 do not need anything about the sender. There is just a common message structure.

That works perfectly and the modules are mutually independend.

like image 159
WeSee Avatar answered Nov 18 '22 04:11

WeSee