我正在使用 Laravel 調用外部 API。這是我的客戶:<?phpuse GuzzleHttp\Client;$client = new Client();$response = $client->request('POST', 'https://example.org/oauth/token', [ 'headers' => [ 'cache-control' => 'no-cache', 'Content-Type' => 'application/x-www-form-urlencoded', ], 'form_params' => [ 'client_id' => '2', 'client_secret' => 'client-secret', 'grant_type' => 'password', 'username' => 'username', 'password' => 'password', ], ]);$accessToken = json_decode((string)$response->getBody(), true)['access_token'];現(xiàn)在我可以用它來獲取一些東西:<?php$response = $client->request('GET', 'https://example.org/api/items/index', [ 'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'Bearer '.$accessToken, ], ]);所以現(xiàn)在我不想再次在每個方法上啟動客戶端。所以也許有一種很酷/類似 Laravel 的方式來$client在特定路由上向控制器提供?我考慮過應用服務提供商或中間件,但我希望看到一個示例 :-)
1 回答

catspeake
TA貢獻1111條經(jīng)驗 獲得超0個贊
也許你可以使用singleton?將您的實現(xiàn)包裝在一個類中,YourHttpClient然后在您AppServiceProvider的 sregister方法中添加:
$this->app->singleton('YourHttpClient', function ($app) {
return new YourHttpClient();
});
然后你應該能夠像這樣在你的控制器構造函數(shù)中輸入提示
class SomeController {
private $client;
public function __construct(YourHttpClient $client) {
$this->client = $client;
}
}
- 1 回答
- 0 關注
- 118 瀏覽
添加回答
舉報
0/150
提交
取消