0

お世話になります。
Laravel起動時に生成したインスタンスをサービスコンテナに登録する方法につきましてご教授ください。

動作環境はsailを使用しています。
versionは以下の通りです。

$ php -v
PHP 7.4.33 (cli) (built: Nov  8 2022 11:33:35) ( NTS )
$ php artisan -V
Laravel Framework 8.83.26

期待する動作は以下の通りです。

  1. app起動
  2. ExampleServiceのインスタンスを生成
  3. 以後サービスコンテナから取り出すときは2で生成したインスタンスを使用して処理する

AppServiceProvider#register 内で rand() を使用した値をserviceに入れるとリクエストの度に新しいランダム値が設定されています。
spl_object_id を使用してインスタンスのidを調べたところ同じidを返すので "同じインスタンス" と理解しています。

こちら を参考にサービスコンテナを登録してます。

  • 説明で使用しているクラスについて
    • ExampleController: serviceが持っている値とserviceのobject_idをjsonにして返す
    • ExampleService: コンストラクタで受け取った値を返す(コンテナに登録するクラス)

ExampleServiceクラスはAppServiceProviderで登録しています。
AppServiceProviderはconfig/app.phpのprovidersに登録しています。

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\ExampleService;
use Illuminate\Http\Request;

class ExampleController extends Controller
{
    private $exampleService;

    public function __construct(ExampleService $exampleService)
    {
        $this->exampleService = $exampleService;
    }

    public function index(Request $request)
    {
        return response()->json([
            // このidは変わらない
            'object_id' => spl_object_id($this->exampleService),
            // こちらはリクエストの度に変わる
            'value' => $this->exampleService->get(),
        ]);
    }
}
<?php
namespace App\Services;

class ExampleService
{
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function get()
    {
        return $this->value;
    }
}
<?php

namespace App\Providers;

use App\Services\ExampleService;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        // $this->app->singletonIfを使用しても結果は同じ
        $this->app->singleton(ExampleService::class, function ($app) {
            $seed = rand();
            // リクエストの度に何故か呼ばれる
            \Log::info($seed);
            return new ExampleService($seed);
        });
    }

    public function boot()
    {

    }
}

よろしくお願いいたします。

0

この質問に回答するには、ログインする必要があります。

のタグが付いた他の質問を参照する。