cos/rest-client-bundle

Symfony rest client bundle - 进行中

安装: 182

依赖: 0

建议者: 0

安全: 0

星标: 10

关注者: 2

分支: 1

开放问题: 1

类型:symfony-bundle

1.0.0 2017-03-18 19:44 UTC

This package is not auto-updated.

Last update: 2024-09-29 02:55:36 UTC


README

Symfony Rest Client Bundle 使用 GuzzleHttpOcramius/ProxyManager

安装

使用Composer安装CosRestClientBundle,请执行以下命令

$ composer require "cos/rest-client-bundle": "dev-master"

现在,Composer将自动下载所有必需的文件,并为您安装它们。接下来,您需要更新您的AppKernel.php文件,并注册新包

<?php

// in AppKernel::registerBundles()
$bundles = array(
    // ...
    new Cos\RestClientBundle\CosRestClientBundle(),
    // ...
);

该包现在已安装。让我们开始配置该包。

配置参考

# config.yml
cos_rest_client:
    annotation_reader: annotation_reader # annotation reader service id
    # http clients and base URLs
    clients:
        default: { baseUri: 'https://jsonplaceholder.typicode.com' }

用法

定义rest资源接口

<?php

namespace AppBundle\Rest;


use Cos\RestClientBundle\Annotation\Client;
use Cos\RestClientBundle\Annotation\Endpoint;
use Cos\RestClientBundle\Annotation\Form;
use Cos\RestClientBundle\Annotation\Json;
use Cos\RestClientBundle\Annotation\Path;
use Cos\RestClientBundle\Annotation\Query;

/**
 * Client configuration  
 * @Client(name="default")
 */
interface Posts
{
    /**
     * @Path(name="id", paramName="idParam")
     * @Endpoint(uri="/posts/{id}", method="get")
     */
    public function get($idParam);

    /**
     * @Query(name="userId")
     * @Endpoint(uri="/posts")
     */
    public function getWithQuery($userId);

    /**
     * @Form(name="formData")
     * @Endpoint(uri="/posts", method="POST")
     */
    public function form(array $formData);

    /**
     * @Json(name="data")
     * @Endpoint(uri="/posts", method="POST")
     */
    public function json(array $data);
}

为Posts创建代理

<?php
    //in controller
    $proxyFactory = $this->get('cos_rest_client.proxy_factory');
    $proxy = $proxyFactory->create(Posts::class);

调用接口中定义的代理方法

<?php
    $proxy->get(1); //request for client base uri + /posts/1
    $proxy->getWithQuery(1)->getBody()->getContents(); //request for /posts?userId=1
    $data = ['foo' => 'bar']
    $proxy->form($data) //post request where $data is sent as application/x-www-form-urlencoded
    $proxy->json($data) // send data as json

响应

来自代理的每个方法调用都返回一个 Psr\Http\Message\ResponseInterface

完整示例

https://github.com/cosminseceleanu/RestClientBundleSample

事件

RequestEvent:在请求执行之前分发
ResponseEvent:在收到响应时分发