为了账号安全,请及时绑定邮箱和手机立即绑定

向控制器提供 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'];现在我可以用它来获取一些东西:<?php$response = $client->request('GET',    'https://example.org/api/items/index', [        'headers' => [            'Accept'        => 'application/json',            'Authorization' => 'Bearer '.$accessToken,        ],    ]);所以现在我不想再次在每个方法上启动客户端。所以也许有一种很酷/类似 Laravel 的方式来$client在特定路由上向控制器提供?我考虑过应用服务提供商或中间件,但我希望看到一个示例 :-)
查看完整描述

1 回答

?
catspeake

TA贡献1111条经验 获得超0个赞

也许你可以使用singleton?将您的实现包装在一个类中,YourHttpClient然后在您AppServiceProvider的 sregister方法中添加:


$this->app->singleton('YourHttpClient', function ($app) {

    return new YourHttpClient();

});

然后你应该能够像这样在你的控制器构造函数中输入提示


class SomeController {

    private $client;


    public function __construct(YourHttpClient $client) {

       $this->client = $client;

    }

}


查看完整回答
反对 回复 2022-06-17
  • 1 回答
  • 0 关注
  • 125 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号