流明观察器不在 eloquent 模型上工作
lumen observer is not working on the eloquent model
我正在使用流明 5.5。我试图让观察者在 updating/deleting 模型时被调用。当我尝试使用用户模型时,观察者没有调用。当我对事件执行此操作时,一切正常。它甚至没有显示任何错误。
这是我的代码:
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
。但运气不好
Lumen 没有观察功能。
您可以改用事件或创建自定义观察器并从您的代码中调用其函数。
在此处阅读文档 - Events
Lumen 不像 Laravel 那样有模型观察者。我同意使用事件或实施您的自定义观察者。如果您选择后者,这里的 post 可能会有所帮助。
https://link.medium.com/ZHsJwJuvC5
我正在使用流明 5.5。我试图让观察者在 updating/deleting 模型时被调用。当我尝试使用用户模型时,观察者没有调用。当我对事件执行此操作时,一切正常。它甚至没有显示任何错误。
这是我的代码:
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
。但运气不好
Lumen 没有观察功能。 您可以改用事件或创建自定义观察器并从您的代码中调用其函数。
在此处阅读文档 - Events
Lumen 不像 Laravel 那样有模型观察者。我同意使用事件或实施您的自定义观察者。如果您选择后者,这里的 post 可能会有所帮助。 https://link.medium.com/ZHsJwJuvC5