尝试获得真正的 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'));
}
}
Route::get('/test1', fn() => app(SingleTest::class)->var);
Route::get('/test2', fn() => app(SingleTest::class)->var);
然后我卷曲 /test1 和 /test2 路线:
test singleton
两次 - 很好。init instance
出现一次。不,我看到 2 条消息,这意味着还创建了 SingleTest 的第二个实例。这不是单身人士。PHP 是一种“无共享架构”,单例不会在 HTTP 请求中持续存在,因为应用程序会根据每个请求重新启动。