Laravel 单例 - 如何只有一个实例

问题描述 投票:0回答:1

尝试获得真正的 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);

然后我卷曲 /test1 和 /test2 路线:

  • 卷曲打印
    test singleton
    两次 - 很好。
  • with log 我希望构造函数只调用一次并且
    init instance
    出现一次。不,我看到 2 条消息,这意味着还创建了 SingleTest 的第二个实例。这不是单身人士。
laravel
1个回答
0
投票

PHP 是一种“无共享架构”,单例不会在 HTTP 请求中持续存在,因为应用程序会根据每个请求重新启动。

© www.soinside.com 2019 - 2024. All rights reserved.