pierrerolland/guzzle-config-operations-bundle

此包允许Symfony项目将Guzzle操作添加到其配置中

v3.2.1 2019-04-17 10:02 UTC

README

Build Status Scrutinizer Code Quality Total Downloads

此包允许Symfony项目将Guzzle操作添加到其配置中。它还使用Symfony或JMS的序列化器将响应直接反序列化为对象。您只需定义您的调用在Yaml中,以及您的模型类来接收响应,任务就完成了!

安装

composer require pierrerolland/guzzle-config-operations-bundle

如果使用Symfony 2/3,在app/AppKernel.php中

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            // ...
            new Guzzle\ConfigOperationsBundle\GuzzleConfigOperationsBundle()
        ];

        return $bundles;
    }

在Symfony 4中的config/bundles.php中

<?php

return [
    // ...
    Guzzle\ConfigOperationsBundle\GuzzleConfigOperationsBundle::class => ['all' => true],
];

在app/config.yml中激活Symfony序列化器

framework:
    serializer: ~

或JMSSerializer

https://github.com/schmittjoh/JMSSerializerBundle http://jmsyst.com/bundles/JMSSerializerBundle

用法

1. 定义您的客户端

# services.yml

services:
    app.client.foo:
        class: GuzzleHttp\Client
        tags:
            - { name: guzzle.client, alias: foo }
        arguments:
            $config:
                baseUrl: "http://foo"
                operations:
                    readBar:
                        httpMethod: "GET"
                        uri: "/bar/{barId}"
                        responseClass: AppBundle\Model\Bar # The model used to deserialize the response
                        parameters:
                            barId:
                                type: "string"
                                location: "uri"
                                required: true
                    # other operations here    
      

标签行很重要,需要name: guzzle.clientalias部分。

2. 使用客户端

将出现一个新的服务,称为guzzle_client.[您使用的别名]。您可以直接调用操作。

   // @var AppBundle\Model\Bar $bar
   $bar = $this->get('guzzle_client.foo')->readBar(['barId' => 1]);

客户端配置

此文档是从Guzzle Services包中提取的。

操作

https://github.com/guzzle/guzzle-services/blob/master/src/Operation.php#L23

参数

https://github.com/guzzle/guzzle-services/blob/master/src/Parameter.php#L84

对象归一化

此包提供了一个递归归一化器。使用类型注解让归一化器知道哪个对象应该被递归填充(数组后缀为[])。

<?php
// Article.php

namespace AppBundle\Model;

use Guzzle\ConfigOperationsBundle\Normalizer\Annotation as Normalizer;

class Article
{
    /**
     * @var Tag[]
     *
     * @Normalizer\Type(name="AppBundle\Model\Tag[]")
     */
    private $tags;

    /**
     * @var Category
     *
     * @Normalizer\Type(name="AppBundle\Model\Category")
     */
    private $category;

    // ...