3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelでsingletonで書いてても既存のインスタンスが使われないケース

Posted at

メモがてら初投稿。
singletonで定義してあっても毎回別のインスタンスになるケースがあって調べてみた。

#環境

  • PHP7.1
  • Laravel 5.5.39

↓のように定義して

        $this->app->singleton(xxxxxClass::class, function ($app, $params) {
            return new xxxxxClass($params);
        });

#実装コード
↓のように呼び出す

        \App::make(
            xxxxxClass::class,
            ['param' => 12345]
        );

この場合は次に同じように呼び出しても既存のインスタンスが使われてない。

理由

laravelのコード見てみたらパラメータつきで指定される毎回作り直しになるっぽい。
(たとえ同じパラメータだったとしても)

vendor/laravel/framework/src/Illuminate/Container/Container.php

    /**
     * Resolve the given type from the container.
     *
     * @param  string  $abstract
     * @param  array  $parameters
     * @return mixed
     */
    protected function resolve($abstract, $parameters = [])
    {
        $abstract = $this->getAlias($abstract);

        $needsContextualBuild = ! empty($parameters) || ! is_null(
            $this->getContextualConcrete($abstract)
        );

        // If an instance of the type is currently being managed as a singleton we'll
        // just return an existing instance instead of instantiating new instances
        // so the developer can keep using the same objects instance every time.
        if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
            return $this->instances[$abstract];
        }
        ~省略~
   }

マニュアルあさってみたりしたけど特に記載は無いけどこれって当たり前だから書いてないのかなぁ。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?