Home  >  Article  >  PHP Framework  >  Quick Start with Laravel Model Events

Quick Start with Laravel Model Events

Guanhui
Guanhuiforward
2020-05-01 13:07:102432browse

Laravel model events allow you to monitor multiple key points in the model life cycle and even prevent a model from being saved or deleted. The Laravel Model Events documentation provides an overview of how to use hooks to associate corresponding events with related event types, but the main focus of this article is the construction and setup of events and listeners, with some additional details.

Event Overview

Eloquent has many events that allow you to connect them using hooks and add custom functionality to your models. The model starts with the following events:

retrieved

creating

created

updating

updated

saving

saved

deleting

deleted

restoring

restored

We can learn about them from the documentation. How is it implemented? You can also enter the base class of Model to see how they are implemented:

When the existing model is retrieved from the database, the retrieved event will be triggered. When a new model is saved for the first time, the creating and created events will fire. If the save method is called on a model that already exists in the database, the updating / updated event will be triggered. Regardless, in both cases, the saving / saved events will fire.

The documentation gives a good overview of model events and explains how to use hooks to associate events, but if you are a beginner or are not familiar with how to use hooks to connect event listeners to these customizations Model events are associated, please read further in this article.

Registering Events

In order to associate an event in your model, the first thing you need to do is to register the event object using the $dispatchesEvents property, which ultimately Will be triggered by HasEvents::fireCustomModelEvent() method, which will be called by fireModelEvent() method. The original fireCustomModelEvent() method is roughly as follows:

/**
 * 为给定的事件触发一个自定义模型。
 *
 * @param  string  $event
 * @param  string  $method
 * @return mixed|null
 */
protected function fireCustomModelEvent($event, $method)
{
    if (! isset($this->dispatchesEvents[$event])) {
        return;
    }
    $result = static::$dispatcher->$method(new $this->dispatchesEvents[$event]($this));
    if (! is_null($result)) {
        return $result;
    }
}

Some events, such as delete, will be detected to determine whether the event will return false and then exit the operation. For example, you can use this hook to do some detection and prevent a user from being created or deleted.

Using the App\User model for example, here shows how to configure your model event:

protected $dispatchesEvents = [
    'saving' => \App\Events\UserSaving::class,
];

You can use the artisan make:event command to create this event for you, but basically this will This is what you end up with:

<?php
namespace App\Events;
use App\User;
use Illuminate\Queue\SerializesModels;
class UserSaving
{
    use SerializesModels;
    public $user;
    /**
     *  创建一个新的事件实例
     *
     * @param \App\User $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

Our event provides a public $user property so that you can access the User model instance during the saving event.

The next thing you need to do in order to make it work is to set up an actual listener for this event. We set the triggering time of the model. When the User model triggers the saving event, the listener will be called.

Create an event listener

Now, we define the User model and register an event listener to listen for the saving event to be triggered. Although I was able to do this quickly with model observers, I want to walk you through configuring event listeners for individual event triggers.

Event Listener Just like other event listeners in Laravel, the handle() method will receive an instance of the App\Events\UserSaving event class.

You can create it manually or use the php artisan make:listener command. Regardless, you will create a listener class like this:

<?php
namespace App\Listeners;
use App\Events\UserSaving as UserSavingEvent;
class UserSaving
{
    /**
     * 处理事件。
     *
     * @param  \App\Events\UserSavingEvent $event
     * @return mixed
     */
    public function handle(UserSavingEvent $event)
    {
        app(&#39;log&#39;)->info($event->user);
    }
}

I just added a logging call to make it easier to inspect the model passed to the listener. To do this, we also need to register a listener in the EventServiceProvider::$listen property:

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
    /**
     * 应用的事件监听器。
     * 
     * @var array
     */
    protected $listen = [
        \App\Events\UserSaving::class => [
            \App\Listeners\UserSaving::class,
        ],
    ];
    // ...
}

Now, when the model calls the saving event, the event listener we registered will also be triggered and executed.

Try event monitoring

We can quickly generate event monitoring code through the tinker session:

php artisan tinker
>>> factory(\App\User::class)->create();
=> App\User {#794
     name: "Aiden Cremin",
     email: "josie05@example.com",
     updated_at: "2018-03-15 03:57:18",
     created_at: "2018-03-15 03:57:18",
     id: 2,
   }

If you have correctly registered the event and listener, You should be able to see the JSON expression of the model in the laravel.log file:

[2018-03-15 03:57:18] local.INFO: {"name":"Aiden Cremin","email":"josie05@example.com"}

One thing to note is that the model does not have created_at or updated_at attributes at this time. If save() is called again on the model, there will be a new record with a timestamp on the log, because the saving event fires on newly created records or existing records:

>>> $u = factory(\App\User::class)->create();
=> App\User {#741
     name: "Eloisa Hirthe",
     email: "gottlieb.itzel@example.com",
     updated_at: "2018-03-15 03:59:37",
     created_at: "2018-03-15 03:59:37",
     id: 3,
   }
>>> $u->save();
=> true
>>>

Stop a save operation

Some model events allow you to perform blocking operations. To give a ridiculous example, suppose we do not allow any user's model to save its attribute $user->name. The content is Paul:

/**
 * 处理事件。
 *
 * @param  \App\Events\UserSaving $event
 * @return mixed
 */
public function handle(UserSaving $event)
{
    if (stripos($event->user->name, &#39;paul&#39;) !== false) {
        return false;
    }
}

In the Model::save() method of Eloquent, it will be based on The return result of event monitoring determines whether to stop saving:

public function save(array $options = [])
{
    $query = $this->newQueryWithoutScopes();
    // 如果 "saving" 事件返回 false ,我们将退出保存并返回
    // false,表示保存失败。这为服务监听者提供了一个机会,
    // 当验证失败或者出现其它任何情况,都可以取消保存操作。
    if ($this->fireModelEvent(&#39;saving&#39;) === false) {
        return false;
    }

This save() is a good example. It tells you how to customize events in the model life cycle and passively perform log data recording or Task scheduling.

Using Observers

If you are listening to multiple events, then you may find it more convenient to use an observer class to group the events by type. Here is an example Eloquent observer:

<?php
namespace App\Observers;
use App\User;
class UserObserver
{
    /**
     * 监听 User 创建事件。
     *
     * @param  \App\User  $user
     * @return void
     */
    public function created(User $user)
    {
        //
    }
    /**
     * 监听 User 删除事件。
     *
     * @param  \App\User  $user
     * @return void
     */
    public function deleting(User $user)
    {
        //
    }
}

You can register an observer in the boot() method of the service provider AppServiceProvider.

/**
 * 运行所有应用服务。
 *
 * @return void
 */
public function boot()
{
    User::observe(UserObserver::class);
}

推荐教程:《Laravel教程

The above is the detailed content of Quick Start with Laravel Model Events. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete