trigger actions when certain conditions are met

Hi all,

I am looking for an elegant way to solve a problem of when A condition is met, do B action

I have 3 different models named: ModelA, ModelB, ModelC

Requirement #1: when an instance of ModelA or ModelB is added or updated (e.g. add a new book or update book title), I want to send email to admin. Note that I dont care about ModelC at all

Requirement #2: when an instance of ModelC meets a specific requirement (e.g. when a review is 1 star), I want to send email to admin

I am thinking about Yii2 Event. EVENT_AFTER_INSERT and EVENT_AFTER_UPDATE are probably the way to go.

Im stucked at how to

#1. make EVENT_AFTER_INSERT and EVENT_AFTER_UPDATE works for ModelA and ModelB. I really dont know how to catch the events ? I want to do such a way that it does not have any duplicates.

#2. How do I check certain attributes in an EVENT in such a way that satisfies the above Requirement #2 ?

Thanks

simple approach would be to create a behavior and use that where you need the callbacks fired




<?php


// MailerBehavior

namespace app\components;


use yii\base\Behavior;


class MailerBehavior extends Behavior

{

    public function events()

    {

        return [

            ActiveRecord::EVENT_AFTER_INSERT => 'sendWelcomeEmail',

        ];

    }


    public function sendWelcomeEmail($event)

    {

        // ...

    }

}




// Models

namespace app\models;


use yii\db\ActiveRecord;

use app\components\MailerBehavior;


class ModelA extends ActiveRecord

{

    public function behaviors()

    {

        return [

            MailerBehavior::className(),

        ];

    }

}



read the docs

http://www.yiiframework.com/doc-2.0/guide-concept-events.html

thanks, excellent and detailed sample