Laravel 模型事件实现原理

Laravel 的 ORM 模型在一些特定的情况下,会触发一系列的事件,目前支持的事件有这些:creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored,那么在底层是如何实现这个功能的呢?

1. 如何使用模型事件

先来看看如何使用模型事件,文档里面写了两种方法,实际上总共有三种方式可以定义一个模型事件,这里以 saved 事件来做例子,其他事件都一样。

  1. events 属性

直接上代码:

class User extends Authenticatable {
        use Notifiable;

        protected $events = [
            'saved' => UserSaved::class,
        ];
}

这个比较难以理解,而且文档并没有详细说明,刚开始以为 saved 被触发后会调用 UserSaved 里面的 handle 方法,实际上并不是。这个数组只是对事件做的一个映射,它定义了在模型的 saved 的时候会触发 UserSaved 这个事件,我们还要定义该事件以及其监听器才可以:

namespace App\Events;
use App\User;

class UserSaved {
    public $user;
    public function __construct(User $user){
        $this->user = $user;
    }
}
namespace App\Listeners;
class UserSavedListener {
    public function handle(UserSaved $userSaved){
        dd($userSaved);
    }
}

然后还要到 EventServiceProvider 中去注册该事件和监听器:

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\UserSaved' => [
            'App\Listeners\UserSavedListener',
        ]
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

    }
}

这样在 saved 节点的时候,UserSaved 事件会被触发,其监听器 UserSavedListener 的 handle 方法会被调用。

  1. 观察者

这是文档比较推崇的一个模型事件定义方法,也比较好理解,先定义一个观察者:

use App\User;

class UserObserver
{
    /**
     * 监听用户创建事件.
     *
     * @param  User  $user
     * @return void
     */
    public function created(User $user)
    {
        //
    }

    /**
     * 监听用户创建/更新事件.
     *
     * @param  User  $user
     * @return void
     */
    public function saved(User $user)
    {
        //
    }
}

然后在某个服务提供者的 boot 方法中注册观察者:

namespace App\Providers;

use App\User;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::observe(UserObserver::class);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

这样在模型事件触发的时候,UserObserver 的相应方法就会被调用。其实,在使用观察者的时候,除了一些系统自带的,我们还可以定义一些自己的事件:

class User extends Authenticatable {
    use Notifiable;

    protected $observables = [
        'customing', 'customed'
    ];
}

然后在观察者里面定义同名方法:

class UserObserver
{

    /**
     * 监听用户创建/更新事件.
     *
     * @param  User  $user
     * @return void
     */
    public function saved(User $user)
    {
        //
    }

    public function customing(User $user){

    }

     public function customed(User $user){

    }
}

由于是我们自己定义的事件,所以触发的时候也必须手动触发,在需要触发的地方调用模型里面的一个 fireModelEvent 方法即可。不过由于该方法是 protected 的,所以只能在自己定义的模型方法里面,当然如果通过反射来调用,或许可以直接在 $user 对象上触发也说不定,这个我没试,大家可以自行测试下。

class User extends Authenticatable {
    use Notifiable;

    protected $observables = [
        'customing', 'awesoming'
    ];

    public function custom(){
        if ($this->fireModelEvent('customing') === false) {
            return false;
        }

        //TODO

         if ($this->fireModelEvent('customed') === false) {
            return false;
        }
    }
}
  1. 静态方法定义

我们还可以通过模型上的对应静态方法来定义一个事件,在 EventServiceProvider 的 boot 方法里面定义:

class EventServiceProvider extends ServiceProvider{

/**
 * Register any events for your application.
 *
 * @return void
 */
public function boot()
{
    parent::boot();

    User::saved(function(User$user) {

    });

    User::saved('UserSavedListener@saved');
}
}

通过静态方法定义的时候,可以直接传递进入一个闭包,也可以定义为某个类的方法,事件触发时候传递进入的参数就是该模型实例。

2. 模型事件实现原理

Laravel 的模型事件所有的代码都在 Illuminate\Database\Eloquent\Concerns\HasEvents 这个 trait 下,先来看看 Laravel 是如何注册这些事件的,其中的 $dispatcher 是一个事件的调度器 Illuminate\Contracts\Events\Dispatcher 实例,在 Illuminate\Database\DatabaseServiceProvider 的 boot 方法中注入。

protected static function registerModelEvent($event, $callback){
        if (isset(static::$dispatcher)) {
            $name = static::class;

            static::$dispatcher->listen("eloquent.{$event}: {$name}", $callback);
        }
    }

这里是 Laravel 事件注册的地方,其中以 eloquent.saved:App\User 为事件名,$callback 作为处理器来注册。这个注册事件的方法,只会注册以观察者和静态方法定义的。假如你定义为模型的 $events 属性的话,Laravel 是不会注册的,会在触发事件的时候同步触发,接下来会分析。

然后在 HasEvents 中定义了一堆的方法如下,这些就是我们上面通过静态方法来定义事件监听器的原理,不多说一看就懂。

public static function saving($callback){
    static::registerModelEvent('saving', $callback);
}

public static function saved($callback){
    static::registerModelEvent('saved', $callback);
}

那么如何通过观察者的形式来定义事件监听器呢?看源码:

    public static function observe($class){
        $instance = new static;

        $className = is_string($class) ? $class : get_class($class);

        foreach ($instance->getObservableEvents() as $event) {
            if (method_exists($class, $event)) {
                static::registerModelEvent($event, $className.'@'.$event);
            }
        }
    }

    public function getObservableEvents()
    {
        return array_merge(
            [
                'creating', 'created', 'updating', 'updated',
                'deleting', 'deleted', 'saving', 'saved',
                'restoring', 'restored',
            ],
            $this->observables
        );
    }

先获取到 observer 的类名,然后判断是否存在事件名对应的方法,存在则调用 registerModelEvent 注册,这里事件名还包括我们自己定义在 observables 数组中的。

事件以及监听器都定义好后,就是如何触发了,前面说到有一个方法 fireModelEvent,来看看源码:

    protected function fireModelEvent($event, $halt = true)
    {
        if (! isset(static::$dispatcher)) {
            return true;
        }

        $method = $halt ? 'until' : 'fire';

        $result = $this->filterModelEventResults(
            $this->fireCustomModelEvent($event, $method)
        );

        if ($result === false) {
            return false;
        }

        return ! empty($result) ? $result : static::$dispatcher->{$method}(
            "eloquent.{$event}: ".static::class, $this
        );
    }

其中比较关键的一个方法是 fireCustomModelEvent,它接受一个事件名以及触发方式。顺带一提,filterModelEventResults 这个方法的作用就是把监听器的返回值为 null 的过滤掉。

看看 fireCustomModelEvent 的源码:

    protected function fireCustomModelEvent($event, $method)
    {
        if (! isset($this->events[$event])) {
            return;
        }

        $result = static::$dispatcher->$method(new $this->events[$event]($this));

        if (! is_null($result)) {
            return $result;
        }
    }

这个就是用来触发我们通过 $events 定义的事件了,假如我们这么定义:

class User extends Model{
    protected $events = [
        'saved'    =>    UserSaved::class
    ]
}

那这里的触发就是:

 $result = static::$dispatcher->fire(new UserSaved($this));

顺带一提,Laravel 中触发事件的方法有两个,一个是常用的 fire,还有一个是 util,这两个的差别就是 fire 会把监听器的返回值返回,而 util 永远返回 null

然后接下来就是会去触发通过观察者和静态方法定义的监听器了,这一段代码:

        if ($result === false) {
            return false;
        }

        return ! empty($result) ? $result : static::$dispatcher->{$method}(
            "eloquent.{$event}: ".static::class, $this
        );

这里会先判断 $events 定义的监听器是否返回 false 以及返回值是否为空,如果为 false 则直接结束事件,如果返回不为 false 而且为空的话,会再去触发通过观察者和静态方法定义的监听器,并且把监听器的返回值返回。

完。

————————————————
原文作者:大张
转自链接:https://learnku.com/articles/5465/event-realization-principle-of-laravel-model
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值