如何解决Lumen / Laravel中的单身人士?

问题描述 投票:2回答:2

我的课程需要API Key(APIClent.php)。

我想初始化APIClient.php并共享实例(单例)

我有两个需要访问初始化实例的控制器(上图)。

现在每次我调用我的控制器时,它都会获得一个类的实例(APIClient)而不是获得一个存在的实例(如果有的话)。

我该如何解决这个问题?这就是我的代码所看到的。

AppServiceProvider.php

public function register()
{
    $this->app->singleton(APIClient::class, function()
    {
        return new APIClient(env('API_KEY'));
    });

}

ListController.php

public function __construct(APIClient $client)
{
    //does the same thing as below
   // $this->apiClient = App(APIClient::class);

   $this->apiClient = $client;
}

web.php

只是这一行

$router->get('lists', ['uses' => 'ListController@index']);

任何提示或资源表示赞赏。

谢谢

php laravel api singleton lumen
2个回答
0
投票

Singleton并不意味着对象将留在内存中,可用于所有客户端请求,直到时间结束。它只是意味着服务器只会在每次请求时创建一次,如果在同一请求期间再次需要该对象,它将使用创建的对象。

Singleton对于不同的用户可能是不同的,并且可能在下一个请求时改变。

您的示例没有演示单例的好处,因为您在控制器的__construct中使用它,并且此函数在每个请求上也只调用一次。


-1
投票
YOU write this : 

public function register()
{
    $this->app->singleton(APIClient::class, function()
    {
        return new APIClient(env('API_KEY'));
    });

}

each time, you call your `APICLient`, you create a new objet. 
If you want to use singleton pattern,
 just put the write code there without using `new` like 
 public function register()
{
    $this->app->singleton(APIClient::class, function()
    {
        return (env('API_KEY'));
    });
}
or Something like that.
© www.soinside.com 2019 - 2024. All rights reserved.