【问题标题】:lumen observer is not working on the eloquent model流明观察者没有在雄辩的模型上工作
【发布时间】:2020-12-23 18:11:40
【问题描述】:

我正在使用流明 5.5。我试图在更新/删除模型时调用观察者。当我尝试使用用户模型时,观察者没有调用。当我对事件执行此操作时,一切正常。它甚至没有显示任何错误。

这是我的代码:

AppServiceProvider.php

....
use App\Models\User;
use App\Observers\UserObserver;
...

public function boot() {
    User::observe(UserObserver::class);

}

App\Models\User.php

...
    public static function changeCustomerStatus(int $customerID): int{
        $customer = self::where([
                'id'        => $customerID,
                'user_type' => app('config')->get('user_type.CUSTOMER')
            ])
            ->first();

        if ($customer) {
            $customer->status = $customer->status == app('config')->get('status.ACTIVE') ? app('config')->get('status.DEACTIVE') : app('config')->get('status.ACTIVE');

            if ($customer->save()) {
                return $customer->status;
            }

            return 0;
        }   
        else 
            return 0;
    }
...

App\Observers\UserObserver.php

<?php

namespace App\Observers;

use App\Models\User;

class UserObserver {

    public function updated(User $user) {
        if ($user->status === app('config')->get('status.DEACTIVE')) {
            app('log')->info('updated');
        }
    }


public function saved(User $user) {
        if ($user->status === app('config')->get('status.DEACTIVE')) {
            app('log')->info('saved');
        }
    }


    public function deleted(User $user) {
        app('log')->info('deleted');
    }
}

我什至做了composer dump-autoload。但没有运气

【问题讨论】:

  • 这个Article 解释了如何将 laravel Observers 带入 lumen。我使用 lumen 8.x 对其进行了测试,它可以工作。

标签: laravel lumen


【解决方案1】:

Lumen 没有观察功能。 您可以改用事件或创建自定义观察者并从您的代码中调用其函数。

在此处阅读文档 - Events

【讨论】:

【解决方案2】:

Lumen 不像 Laravel 那样有模型观察者。我同意使用事件或实现您的自定义观察者。如果您选择使用后者,这里有一篇文章可能会有所帮助。 https://link.medium.com/ZHsJwJuvC5

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多