第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

向控制器提供 API-Client

向控制器提供 API-Client

PHP
守候你守候我 2022-06-17 15:40:26
我正在使用 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;

    }

}


查看完整回答
反對 回復 2022-06-17
  • 1 回答
  • 0 關注
  • 118 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號