mapado/rest-client-sdk-bundle

hydra API 的 Rest 客户端 SDK Bundle

安装次数: 17,499

依赖项: 0

建议者: 0

安全性: 0

星标: 5

关注者: 9

分支: 1

开放问题: 4

类型:symfony-bundle

v2.0.1 2024-07-29 15:16 UTC

README

Symfony 扩展包,用于mapado/rest-client-sdk

安装

composer require mapado/rest-client-sdk-bundle

Symfony flex

将其添加到 config/bundle.php

return [
    // ...
    Mapado\RestClientSdkBundle\MapadoRestClientSdkBundle::class => ['all' => true],
];

不使用 flex

将其添加到 AppKernel.php

    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Mapado\RestClientSdkBundle\MapadoRestClientSdkBundle(),
        )

        // ...

使用方法

在您的配置文件中添加以下内容

Symfony Flex: config/packages/mapado_rest_client_sdk.yaml,非 flex: app/config/config.yml

mapado_rest_client_sdk:
    # debug: %kernel.debug%
    # cache_dir: '%kernel.cache_dir%/mapado/rest_client_sdk_bundle/'
    entity_managers:
        foo:
            server_url: 'http://foo.com:8080'
            request_headers:
                MyHeader: 'MyValue'
            mappings:
                prefix: /v1
                configuration:
                    collectionKey: 'items' # default is "hydra:member"
                dir: '%kernel.root_dir%/../src/Foo/Bar/Entity/'
            cache:
                cache_item_pool: 'psr6_cache_provider' # default is null
                cache_prefix: 'my_prefix' # default is null

该扩展包为每个定义的实体管理器注册一个服务(在本例中只为 foo 注册了一个)。

服务名称将是: mapado.rest_client_sdk.<manager_name>

由于我命名了我的实体管理器为 foo,因此在此处的服务名称将为: mapado.rest_client_sdk.foo

如果您使用 Symfony 3.3+ 的自动注入功能,您可能希望别名如下

services:
    # ...
    Mapado\RestClientSdk\SdkClient: '@mapado.rest_client_sdk.foo'

如果您有多个实体管理器,Symfony 文档解释了如何处理同一类型的多个实现

想象一下,我有一个以下模型,如组件文档中定义的那样

/**
 * @Rest\Entity(key="carts", client="Acme\Foo\Bar\CartClient")
 */
class Cart {
    // ...
}

我现在可以这样做

$cartList = $this->get('mapado.rest_client_sdk.foo')
    ->getRepository('carts')
    ->findAll(); // `carts` is the `key` defined in the model

$cart = $this->get('mapado.rest_client_sdk.foo')
    ->getRepository('carts')
    ->find(1);

有关使用方法的更多信息,我建议您查看组件文档

使用缓存

通过向 cache.cache_item_pool 提供一个 Psr6 Psr\Cache\CacheItemPoolInterface,每个实体和实体列表都会存储在缓存中。

例如,在 Mapado,我们使用以下Symfony Array 缓存适配器

services:
    cache.rest_client_sdk:
        class: 'Symfony\Component\Cache\Adapter\ArrayAdapter'
        arguments:
            - 0
            - false # avoid serializing entities

mapado_rest_client_sdk:
    entity_managers:
        foo:
            server_url: '%server.url%'
            mappings:
                prefix: /v1
                dir: '%kernel.root_dir%/../src/Mapado/Foo/Model/'
            cache:
                cache_item_pool: 'cache.rest_client_sdk' # the id of the cache service
                cache_prefix: 'mapado_rest_client_'

重写默认 HTTP 客户端

有时,您需要重写基本 HTTP 客户端。在 Mapado,我们喜欢为我们的 API 调用添加当前页面作为 Referrer,传递当前 Accept-Language 标头,或发送 Authorization

由于 HTTP 客户端是自动生成的,唯一的做法就是装饰您的默认客户端

# config/services.yaml or app/config/service.yml

mapado.rest_client_sdk.decorating_ticketing
services:
  # ... 
  mapado.rest_client_sdk.decorating_foo_http_client:
      class:     'App\Rest\Decorator\DecoratingClient'
      decorates: 'mapado.rest_client_sdk.foo_http_client'
      arguments: ['@mapado.rest_client_sdk.decorating_foo_http_client.inner']
      public:    true
<?php

namespace App\Rest\Decorator;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class DecoratingClient implements ClientInterface
{
    /**
     * @var Client
     */
    private $decoratedClient;
    
    public function __construct(Client $decoratedClient)
    {
        $this->decoratedClient = $decoratedClient;
    }
    
    /**
     * {@inheritdoc}
     */
    public function send(RequestInterface $request, array $options = []): ResponseInterface
    {
        return $this->decoratedClient->send($request, $options);
    }

    /**
     * {@inheritdoc}
     */
    public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface
    {
        return $this->decoratedClient->sendAsync($request, $options);
    }

    /**
     * {@inheritdoc}
     */
    public function request($method, $uri, array $options = []): ResponseInterface
    {
        if (!isset($options['headers'])) {
            $options['headers'] = [];
        }

        $options['headers'] = array_merge(
            $options['headers'],
            [
                'Authorization' => 'Bearer my-great-token',
                'Accept-Language' => 'fr',
            ]
        );

        return $this->decoratedClient->request($method, $uri, $options);
    }

    /**
     * {@inheritdoc}
     */
    public function requestAsync($method, $uri, array $options = []): PromiseInterface
    {
        return $this->decoratedClient->requestAsync($method, $uri, $options);
    }

    public function getConfig($option = null)
    {
        return $this->decoratedClient->getConfig($option);
    }
}