无法在 Laravel 中找到观察者
Unable to find observer in Laravel
我尝试如下在 AppServiceProvider
中注册我的 ObserverHelper
,但出现以下错误。
Unable to find observer: App\Helpers\App\Observers\FileLogObserver
AppServiceProvider.php
use Illuminate\Support\ServiceProvider;
use App\Helpers\ObserverHelper;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
}
public function boot()
{
ObserverHelper::register();
}
}
ObserverHelper.php
namespace App\Helpers;
class ObserverHelper
{
protected static $observers = [
'App\Models\FileLogs' => App\Observers\FileLogObserver::class,
];
public static function register()
{
foreach (self::$observers as $model => $observer) {
$model::observe($observer);
}
}
}
尝试在 App\Observers\FileLogObserver::class
前面添加一个 \
(引用全局命名空间的反斜杠),或者导入 class.
带反斜杠(引用全局命名空间):
<?php
namespace App\Helpers;
class ObserverHelper
{
protected static $observers = [
'App\Models\FileLogs' => \App\Observers\FileLogObserver::class,
];
public static function register()
{
foreach(self::$observers as $model => $observer) {
$model::observe($observer);
}
}
}
或导入:
<?php
namespace App\Helpers;
use App\Observers\FileLogObserver;
class ObserverHelper
{
protected static $observers = [
'App\Models\FileLogs' => FileLogObserver::class,
];
public static function register()
{
foreach(self::$observers as $model => $observer) {
$model::observe($observer);
}
}
}
注意:即使您的代码是有效的解决方案,也请考虑创建一个单独的提供程序来定义观察者(例如ObserverServiceProvider
)。
我尝试如下在 AppServiceProvider
中注册我的 ObserverHelper
,但出现以下错误。
Unable to find observer: App\Helpers\App\Observers\FileLogObserver
AppServiceProvider.php
use Illuminate\Support\ServiceProvider;
use App\Helpers\ObserverHelper;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
}
public function boot()
{
ObserverHelper::register();
}
}
ObserverHelper.php
namespace App\Helpers;
class ObserverHelper
{
protected static $observers = [
'App\Models\FileLogs' => App\Observers\FileLogObserver::class,
];
public static function register()
{
foreach (self::$observers as $model => $observer) {
$model::observe($observer);
}
}
}
尝试在 App\Observers\FileLogObserver::class
前面添加一个 \
(引用全局命名空间的反斜杠),或者导入 class.
带反斜杠(引用全局命名空间):
<?php
namespace App\Helpers;
class ObserverHelper
{
protected static $observers = [
'App\Models\FileLogs' => \App\Observers\FileLogObserver::class,
];
public static function register()
{
foreach(self::$observers as $model => $observer) {
$model::observe($observer);
}
}
}
或导入:
<?php
namespace App\Helpers;
use App\Observers\FileLogObserver;
class ObserverHelper
{
protected static $observers = [
'App\Models\FileLogs' => FileLogObserver::class,
];
public static function register()
{
foreach(self::$observers as $model => $observer) {
$model::observe($observer);
}
}
}
注意:即使您的代码是有效的解决方案,也请考虑创建一个单独的提供程序来定义观察者(例如ObserverServiceProvider
)。