【问题标题】:Best Practices or Convention for File Structure for API ClientAPI 客户端文件结构的最佳实践或约定
【发布时间】:2017-08-24 03:20:17
【问题描述】:

我是 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 安排。

【问题讨论】:

    标签: php laravel guzzle


    【解决方案1】:

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

    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..."
        ]
    ]
    

    【讨论】:

    • 再次,请原谅我是 Laravel n00b,但我的课程似乎不是服务,而是客户端。
    • 是的。不要担心这个。另一个选项是放在 Repositories 命名空间中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 2021-05-12
    • 1970-01-01
    • 2021-03-15
    相关资源
    最近更新 更多