【问题标题】:Provide API-Client to Controller向控制器提供 API-Client
【发布时间】:2019-12-15 12:26:20
【问题描述】:

我正在使用 Laravel 调用外部 API。

这是我的客户:

<?php

use 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

我考虑过应用服务提供商或中间件,但我希望看到一个示例 :-)

【问题讨论】:

    标签: php laravel laravel-6


    【解决方案1】:

    也许你可以使用singleton?将您的实现包装在一个类中让我们说YourHttpClient 然后在您的AppServiceProviders register 方法中添加:

    $this->app->singleton('YourHttpClient', function ($app) {
        return new YourHttpClient();
    });
    

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

    class SomeController {
        private $client;
    
        public function __construct(YourHttpClient $client) {
           $this->client = $client;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多