在Laravel上使用模型的全局事件

It's basically what I need: if any model row on my project is created, updated or removed, I need call a callback to work with this model row. I'll use that to create a changelog in other model, that will not trigger this global event to avoid looping.

I tried set it like that:

Model::creating($callback);

But it doesn't worked. Work only if I set it directly to all models that I have. It's bad because I need specific one-by-one. If I create a new one, I need specify it manually. Example:

User::creating($callback);
Company::creating($callback);
...

Any change will be logged on another model, called Log. It'll not trigger this $callback, because it'll register on table logs (managed by Log) each change in other models. Something like:

$user = new User;
$user->name = "John";
$user->age = 18;
$user->save();

$user->name = "John Doe";
$user->save();

$user->delete();
$user->restore();
$user->forceDelete();

I'll register something like:

id | object_type | object_id | event_type | object_data
..   App\User      1           created      { name: John, age: 18 }
..   App\User      1           updated      { name: John Doe }
..   App\User      1           trashed      null
..   App\User      1           restored     null
..   App\User      1           removed      null

All Eloquent model events have the format eloquent.event:ClassName.

You could subscribe to the eloquent.* event. Event::listen('eloquent.*', function($model) {});

Then you can check if the current model is a log model (in which case you'd return true straight out of it to avoid infinite recursion), otherwise, save the change to your log model.

With Laravel 5.1

BaseTrait Trait:

trait BaseTrait
{
    public static function bootBaseTrait()
    {

        static:creating(function($item) {
            ....
        });

        static:updating(function($item) {
            ....
        });
    }

    // It binds the events in bootBaseTrait to any subclass
    // Base run first, then run your subclass's events if you defined on the subclass
}

Base Model:

use XX\XX\BaseTrait;
use Illuminate\Database\Eloquent\Model;

class Base extends Model
{
    use BaseTrait;
}

XXX Model:

use XX\XX\Base;

class XXX extends Base
{
}

How does this work?

You can see /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php

protected static function bootTraits()

The method tries to call bootTraitName when you use a trait!