kettasoft/booter

Laravel模型事件Booter包提供了一种灵活的方式来组织和管理工作在Laravel应用程序中的模型事件。它允许开发人员通过将它们与自定义类关联来定义模型事件(如创建、更新、删除等)的特定操作。该包简化了...

v1.0.2 2024-10-02 02:06 UTC

This package is auto-updated.

Last update: 2024-10-03 00:40:58 UTC


README

Laravel模型事件Booter是一个包,它通过允许您定义和映射模型事件(例如,createdupdateddeleted等)到自定义类来简化了在Laravel中管理模型事件。这些类处理与这些事件相关的逻辑,使您的代码更干净、模块化且易于维护。

Sponsor Latest Stable Version Total Downloads License tests

功能

  • 自动启动并触发具有自定义逻辑的模型事件。
  • 将特定事件的逻辑组织到单独的、可重用的类中。
  • 与Laravel内置的模型事件(createdupdateddeleted等)兼容。
  • 易于使用的HasBooter特性,处理事件触发。

安装

    • 通过Composer安装此包
composer require kettasoft/booter
    • HasBooter特性添加到您希望管理事件的任何模型中。
    • 在模型中定义$events数组以将事件映射到处理它们的类。
    • 通过运行以下命令发布包的配置文件:
php artisan vendor:publish --provider="Scaffolding\Booter\Providers\BooterServiceProvider" --tag=config

用法

    • HasBooter特性添加到您的模型中

    • 在模型中使用HasBooter特性以启用事件处理

use Scaffolding\Booter\Traits\HasBooter;

class Post extends Model
{
    use HasBooter;

    /**
     * The event-to-class mappings.
     *
     * @var array
     */
    protected static $events = [
        'created' => [
            \App\Boot\AttachAuthorIdBoot::class,
        ],
        'updated' => [
            \App\Boot\LogChangesBoot::class,
        ],
    ];
}
    • 创建事件处理器类为要处理的事件创建一个类。每个类都应该有一个handle方法,在其中定义当事件被触发时要运行的逻辑。
namespace App\Boots;

use Scaffolding\Booter\HasBooter;

class AttachAuthorIdBoot extends HasBooter
{
    /**
     * Handle the model event.
     *
     * @param  \Illuminate\Database\Eloquent\Model $model
     * @return void
     */
    public function handle(\Illuminate\Database\Eloquent\Model $model)
    {
        // Custom logic for 'created' event
        $model->author_id = auth()->id();
        $model->save();
    }
}

在事件中定义的类将在事件发生时自动被调用。

    • 处理多个事件

您可以为单个模型在$events数组中定义多个事件。每个事件可以有一个或多个类,这些类将被按顺序触发。

protected static $events = [
    'created' => [
        \App\Boot\AttachAuthorIdBoot::class,
        \App\Boot\SendNotificationBoot::class,
    ],
    'updated' => [
        \App\Boot\LogChangesBoot::class,
    ],
];
    • 事件处理流程

    • 当模型事件(如createdupdated等)被触发时,该包自动触发相关的类。

    • 每个类都必须有一个handle方法,在其中实现自定义逻辑。

贡献

欢迎贡献!如果您发现任何问题或对改进有想法,请随时提交一个拉取请求或打开一个问题。

许可证

此包是开源软件,许可协议为MIT。