API客户端

时间:2017-08-23 18:41:10

标签: php laravel guzzle

我是Laravel的新手,需要为我的应用程序将要使用的API编写客户端。

我发现很多关于在控制器操作中实例化Guzzle客户端的帖子。在我看来,我应该编写一个使用API​​的类,然后在控制器操作中使用该类,该操作将结果加载到我的数据库中。我觉得它可能会在app/Http/目录下的某个地方。或许Clients

所以app/Http/Clients/Api.php看起来像这样:

namespace App\Http\Clients;

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

class ApiClient extends Client
{
}

生成的控制器操作将与cron一起安排。

1 个答案:

答案 0 :(得分:2)

您可以创建一个Services命名空间,如下所示:

namespace App\Services;

use GuzzleHttp\Client;

class MyApiWrapper
{
    public function __construct() {
        $this->client = new Client([
            'base_url' => 'https://your-api-domain.com'
        ]);
    }

    public function getComments($postId)
    {
        $uri = sprintf("/posts/{$postId}/comments");

        $response = $this->client->request('GET', $uri);

        return json_decode($response->getBody(), true);
    }
}

然后在你的控制器中,你可以这样做:

use App\Services\MyApiWrapper;

class SomeController
{
    public function index()
    {
        $comments = (new MyApiWrapper)->getComments($postId = 123);
        return $comments;
    }
}

这将返回这样的内容:

[
    [
        "id": 1,
        "user_id": 987,
        "post_id": 123,
        "body": "Lorem ipsum dolor sit amet..."
    ],
    [
        "id": 2,
        "user_id": 876,
        "post_id": 123,
        "body": "Lorem ipsum dolor sit amet..."
    ],
    [
        "id": 3,
        "user_id": 765,
        "post_id": 123,
        "body": "Lorem ipsum dolor sit amet..."
    ]
]