尝试获取真正的 Laravel 单例:
- 服务等级:
<?php
namespace App\Services;
use Illuminate\Support\Facades\Log;
class SingleTest
{
public function __construct(
public string $var
) {
Log::info('init instance');
}
}
- 将此服务注册为单例:
<?php
namespace App\Providers;
use App\Services\SingleTest;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(SingleTest::class, fn() => new SingleTest('test singleton'));
}
}
- 我的检查路线(web.php):
Route::get('/test1', fn() => app(SingleTest::class)->var);
Route::get('/test2', fn() => app(SingleTest::class)->var);
然后我 curl /test1 和 /test2 路由:
- 卷曲打印
test singleton
两次 - 很好。 - 根据日志,我期望构造函数仅被调用一次并
init instance
出现一次。不,我看到 2 条消息,这意味着也创建了 SingleTest 的第二个实例。它不是单例。