簡體   English   中英

如何解決Lumen / Laravel中的單例?

[英]How to resolve singleton in Lumen/Laravel?

我有需要API密鑰(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']);

任何提示或資源表示贊賞。

謝謝

Singleton並不意味着該對象將保留在所有客戶端請求可用的內存中,直到時間結束。 這僅意味着服務器在每次請求時只會創建一次,並且如果在同一請求期間再次需要該對象,它將使用創建的對象。

對於不同的用戶,單例可能會有所不同,並且可能在下一個請求時發生更改。

您的示例未展示單例的好處,因為您正在控制器的__construct中使用單例,並且此函數在每次請求時也僅被調用一次。

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM