swisnl/json-api-client-laravel

一个PHP包,用于将远程JSON:API资源映射到类似Eloquent的模型和集合。

1.2.1 2024-03-05 09:25 UTC

This package is auto-updated.

Last update: 2024-09-05 10:43:34 UTC


README

PHP from Packagist Latest Version on Packagist Software License Buy us a tree Build Status Scrutinizer Coverage Scrutinizer Code Quality Made by SWIS

此包包含一些针对Laravel的特定类,以简化使用swisnl/json-api-client的过程。

安装

composer require swisnl/json-api-client-laravel

注意。在安装此包之前,请确保您已安装PSR-18 HTTP客户端和PSR-17 HTTP工厂,或者同时安装它们,例如:composer require swisnl/json-api-client-laravel guzzlehttp/guzzle:^7.3

HTTP客户端

借助PSR-18 HTTP客户端PSR-17 HTTP工厂,我们从任何HTTP消息客户端中解耦。这需要额外的包提供psr/http-client-implementationpsr/http-factory-implementation。例如,要使用Guzzle 7,只需要求guzzlehttp/guzzle

composer require guzzlehttp/guzzle:^7.3

查看绑定客户端,如果您想使用自己的HTTP客户端或使用特定的配置选项。

服务提供者和外观别名

Laravel会自动发现所需的服务提供者和一些外观别名。但是,如果您已禁用包自动发现,则必须将服务提供者和可选的外观别名添加到您的config/app.php文件中

'providers' => [
    ...,
    \Swis\JsonApi\Client\Providers\ServiceProvider::class,
],
'aliases' => [
    ...,
    'DocumentFactory' => \Swis\JsonApi\Client\Facades\DocumentFactoryFacade::class,
    'DocumentParser' => \Swis\JsonApi\Client\Facades\DocumentParserFacade::class,
    'ItemHydrator' => \Swis\JsonApi\Client\Facades\ItemHydratorFacade::class,
    'ResponseParser' => \Swis\JsonApi\Client\Facades\ResponseParserFacade::class,
    'TypeMapper' => \Swis\JsonApi\Client\Facades\TypeMapperFacade::class,
],

配置

以下是该包提供的默认配置

return [
    /*
    |--------------------------------------------------------------------------
    | Base URI
    |--------------------------------------------------------------------------
    |
    | Specify a base uri which will be prepended to every URI.
    |
    | Default: empty string
    |
    */
    'base_uri' => '',
];

如果您想更改默认配置,请发布并编辑配置文件

php artisan vendor:publish --provider="Swis\JsonApi\Client\Providers\ServiceProvider" --tag="config"

入门

只需让容器注入DocumentClient即可!

use Swis\JsonApi\Client\DocumentClient;

class RecipeController extends Controller
{
    public function index(DocumentClient $client)
    {
        $document = $client->get('https://cms.contentacms.io/api/recipes');
    
        /** @var \Swis\JsonApi\Client\Collection&\Swis\JsonApi\Client\Item[] $recipes */
        $recipes = $document->getData();
        
        foreach ($recipes as $recipe) {
            // Do stuff with the recipe
        }
    }
}

有关更多信息,请参阅swisnl/json-api-client

Laravel HTTP客户端

如果您更喜欢,也可以使用Laravel内置的HTTP客户端。请注意,这需要Laravel 7+。

use Illuminate\Support\Facades\Http;
use Swis\JsonApi\Client\Facades\DocumentFactoryFacade;
use Swis\JsonApi\Client\Item;

$recipe = (new Item())
    ->setType('recipes')
    ->fill([
        'title' => 'Frankfurter salad with mustard dressing',
    ]);

$document = Http::asJsonApi() // Sets the Content-Type and Accept headers to 'application/vnd.api+json'.
    ->post('https://cms.contentacms.io/api/recipes', DocumentFactoryFacade::make($recipe))
    ->jsonApi(); // Parses the response into a JSON:API document.

服务提供者

\Swis\JsonApi\Client\Providers\ServiceProvider注册了TypeMapperJsonApi\Parser以及两个客户端:ClientDocumentClient。每个部分都可以被重写以允许扩展自定义。

绑定TypeMapper

服务提供者将\Swis\JsonApi\Client\TypeMapper注册为单例,因此您的整个应用程序都有相同的映射可用。

映射类型

您可以使用TypeMapper手动注册项目,或使用提供的TypeMapperServiceProvider

use Swis\JsonApi\Client\Providers\TypeMapperServiceProvider as BaseTypeMapperServiceProvider;

class TypeMapperServiceProvider extends BaseTypeMapperServiceProvider
{
    /**
     * A list of class names implementing \Swis\JsonApi\Client\Interfaces\ItemInterface.
     *
     * @var string[]
     */
    protected $items = [
        \App\Items\Author::class,
        \App\Items\Blog::class,
        \App\Items\Comment::class,
    ];
}

绑定客户端

服务提供者将ClientDocumentClient注册到您的应用程序中。默认情况下,Client使用php-http/discovery来查找可用的HTTP客户端、请求工厂和流工厂,因此您不需要自己设置这些。您可以通过自定义容器绑定来指定自己的HTTP客户端、请求工厂或流工厂。这是一种向HTTP客户端添加额外选项或为您的测试注册模拟HTTP客户端的绝佳方式。

class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
    public function register()
    {
        $this->app->bind(\Swis\JsonApi\Client\Client::class, function ($app) {
            if ($app->environment('testing')) {
                $httpClient = new \Swis\Http\Fixture\Client(
                    new \Swis\Http\Fixture\ResponseBuilder('/path/to/fixtures')
                );
            } else {
                $httpClient = new \GuzzleHttp\Client(
                    [
                        'http_errors' => false,
                        'timeout' => 2,
                    ]
                );
            }
    
            return new \Swis\JsonApi\Client\Client($httpClient);
        });
    }
}

注意。本示例在测试环境中使用我们的 swisnl/php-http-fixture-client。此包允许您轻松使用静态固定值模拟请求。绝对值得一试!

变更日志

有关最近变更的更多信息,请参阅 CHANGELOG

测试

composer test

贡献

有关详细信息,请参阅 CONTRIBUTINGCODE_OF_CONDUCT

安全

如果您发现任何与安全相关的问题,请通过电子邮件 security@swis.nl 而不是使用问题跟踪器。

许可证

MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件

此包是 Treeware。如果您在生产环境中使用它,我们请求您为我们买一棵树以感谢我们的工作。通过为 Treeware 森林做出贡献,您将为当地家庭创造就业机会并恢复野生动物栖息地。

SWIS ❤️ 开源

SWIS 是一家来自荷兰莱顿的网页代理机构。我们热爱与开源软件合作。