artificertech/laravel-relationship-events 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

artificertech/laravel-relationship-events

Composer 安装命令:

composer require artificertech/laravel-relationship-events

包简介

Missing relationship events for Laravel

README 文档

README

Missing relationship events for Laravel

This package was intitally forked from https://github.com/chelout/laravel-relationship-events which is not being actively developed. This package is a different take on the original idea that allows relationship event listeners to be created on a per-relationship basis

This package is still in development. Feel free to contribute by submitting a pull request

Build Status Total Downloads Latest Stable Version License

Install

  1. Install package with composer

Latest Release:

Currently there are no releases for this project as it is still in development.

composer require artificertech/laravel-relationship-events

Development branch:

composer require artificertech/laravel-relationship-events:dev-master
  1. Add the HasRelationshipEvents trait to your model
use Artificertech\RelationshipEvents\Concerns\HasRelationshipEvents;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasRelationshipEvents;

    public static function boot()
    {
        parent::boot();

        /**
         * hasOne
         */
        static::hasOneSaved('profile', function ($user, $profile) {
            dump('hasOneSaved', $user, $profile);
        });
    }

    public function profile()
    {
        return $this->hasOne(Profile::class)->withEvents();
    }

}

For all saving, attaching, creating, etc events that are fired before the operation takes place you may return false from the event listener to cancel the operation

use Artificertech\RelationshipEvents\Concerns\HasRelationshipEvents;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasRelationshipEvents;

    public static function boot()
    {
        parent::boot();

        /**
         * hasMany
         */
        static::hasManyCreating('posts', function ($user, $post) {
            if ($post->name == 'badName') return false;
        });
    }

    public function posts()
    {
        return $this->hasMany(Post::class)->withEvents();
    }

}
  1. Dispatchable relationship events. It is possible to fire event classes via $dispatchesEvents properties
use Artificertech\RelationshipEvents\Concerns\HasRelationshipEvents;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasRelationshipEvents;

    protected $dispatchesEvents = [
        'postsCreating' => UserPostsCreating::class,
        'postsCreated' => UserPostsCreated::class,
        'postsSaving' => UserPostsSaving::class,
        'postsSaved' => UserPostsSaved::class,
    ];

    public function posts()
    {
        return $this->hasMany(Post::class)->withEvents();
    }

}

Observers

It is possible to use relationship events in Laravel observers classes Usage is very simple. Define observer class:

namespace App\Observer;

class UserObserver
{
    /**
     * Handle the User "postsCreating" event.
     *
     * @param \App\Models\User $user
     * @param \App\Models\Post $post
     *
     * @return void
     */
    public function postsCreating(User $user, Post $post)
    {
        Log::info("Creating post: {$post->name} for user {$user->name}.");
    }

    /**
     * Handle the User "postsCreated" event.
     *
     * @param \App\Models\User $user
     * @param \App\Models\Post $post
     *
     * @return void
     */
    public function postsCreated(User $user, Post $post)
    {
        Log::info("Post: {$post->name} for user: {$user->name} has been created.");
    }

    /**
     * Handle the User "postsCreating" event.
     *
     * @param \App\Models\User $user
     * @param \App\Models\Post $post
     *
     * @return void
     */
    public function postsSaving(User $user, Post $post)
    {
        Log::info("Saving post: {$post->name} for user {$user->name}.");
    }

    /**
     * Handle the User "postsCreated" event.
     *
     * @param \App\Models\User $user
     * @param \App\Models\Post $post
     *
     * @return void
     */
    public function postsSaved(User $user, Post $post)
    {
        Log::info("Post: {$post->name} for user: {$user->name} has been saved.");
    }
}

Detecting observable events

the laravel-relationship-events package cannot automatically detect relationship events that you want to observe. Please define them in your model class like so:

class User extends Model
{
    use HasRelationshipEvents;

    /**
     * User exposed observable events.
     *
     * These are extra user-defined events observers may subscribe to.
     *
     * @var array
     */
    protected $observables = [
        'postsCreating',
        'postsCreated',
        'postsSaving',
        'postsSaved',
    ];

    public function posts()
    {
        return $this->hasMany(Post::class)->withEvents();
    }

}

Don't forget to register an observer in the boot method of your AppServiceProvider:

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
// ...
    public function boot()
    {
        User::observe(UserObserver::class);
    }
// ...
}

And now just create profile for user:

// ...
$user = factory(User::class)->create([
    'name' => 'John Smith',
]);

// Create profile and assosiate it with user
// This will fire two events hasOneCreating, hasOneCreated
$user->post()->create([
    'name' => 'My first post!',
]);
// ...

Customizing the event name

By default the relationship event name is equal to the relationship function name with the action taking place in camel case. For example if you have a HasOne relationship "profile" then the event names would be "profileCreating", "profileCreated", "profileSaving", "profileSaved".

You may customize the event name by passing the relationship name into the withEvents() function as a string. For example:

class User extends Model
{
    use HasRelationshipEvents;

    public function posts()
    {
        return $this->hasMany(Post::class)->withEvents('userPost');
    }

}

will fire "userPostCreating", "userPostCreated", "userPostSaving", "userPostSaved" events

Relationship Specific info

Each relationship as slightly different events. For example the belongsTo relationship fires {relationship}Associating, {relationship}Associated, {relationship}Dissociating, and {relationship}Dissociated events

Todo

  • Fix Automated Tests
  • Add documentation for ManyToMany type events (these events can be handled by the built in pivot models and do not need this package)
  • Non-Default event name tests
  • Event Dispatcher Tests
  • Event Listener Exception Tests
  • HasOneThrough & HasManyThrough
  • New HasOneOfMany relationship?

artificertech/laravel-relationship-events 适用场景与选型建议

artificertech/laravel-relationship-events 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 18.8k 次下载、GitHub Stars 达 12, 最近一次更新时间为 2021 年 05 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「events」 「laravel」 「relations」 「relationship」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 artificertech/laravel-relationship-events 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 artificertech/laravel-relationship-events 我们能提供哪些服务?
定制开发 / 二次开发

基于 artificertech/laravel-relationship-events 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 18.8k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 12
  • 点击次数: 10
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 12
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-05-15