加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何使用DTO在PHP中使用REST API?

发布时间:2020-12-13 22:54:22 所属栏目:PHP教程 来源:网络整理
导读:我有一个API用于为二手车提供融资报价的服务.我的应用程序是用 PHP编写的,我通过Composer添加了Guzzle 5. 我之前使用过其他API,它们只使用XML或只发送一个POST参数数组,但这个API更复杂. 此API使用DTO对象,文档说明: relies heavily on DTOs to carry data
我有一个API用于为二手车提供融资报价的服务.我的应用程序是用 PHP编写的,我通过Composer添加了Guzzle 5.

我之前使用过其他API,它们只使用XML或只发送一个POST参数数组,但这个API更复杂.

此API使用DTO对象,文档说明:

relies heavily on DTOs to carry data between client and server. The following
sections detail the DTOs. Each web service will serialise and transfer them in their own
formats/methods. It is the responsibility of the client application to correctly construct requests and
parse responses. It is suggested that object serialization and deserialization be used for easier usage.

所以我不知道如何用Guzzle实现这一目标.一些枚举类型是诸如“RequestAssetMotorVehicle”之类的东西.你会在PHP中使用StdClass或Arrays吗?还是上课?我该如何序列化?

Guzzle Docs

解决方法

没有API的文档,这很难表达.但我会试试.我们将使用基于JSON的通用REST API

DTO标准通常是每个公司,有时是每个应用程序.简而言之:DTO是一个序列化对象.

假设这是一个POST请求(我们正在创建一个新用户)

{
   'name':'john','foo':'bar','site':'stackoverflow.com'
}

那个JSON是一个DTO.现在让我们做一个GET

{
   'error':false,'results':2,'data': [{'name':'john','site':'stackoverflow.com'},{'name':'mark','site':'notstackoverflow.com'}]
}

‘data’数组是DTO数组.

那么dox告诉你的是你需要通过创建一个层来传递你的应用程序和API,以便在你身边形成对象,同一层应该把一个对象转化为DTO. .在某些情况下,您可以使用简单的代码处理来自API的响应,但是在某种情况下,GET请求将返回超过10个您想要用某个类解析它的结果.基本上为DTO创建ORM.

就guzzle而言:将正文设置为通过图层推送数据的结果.

public function createUserWithSomeApi()
{
    $g= new GuzzleClient();
    $response = $g->post('http://api.some.place/v1/users',[
                'body' => (new strangeApiDtoParser)->prepare($new_user_data)  
                                         ]);
    return ApiDtoParser::fromDTO($response->getBody());
}

并收到

public function getUsersFromSomeApi()
{
    $g= new GuzzleClient();
    $response = $g->get('http://api.some.place/v1/users',[
             'query' => ['foo' => 'bar']
                          ]);
    return ApiDtoParser::fromDTO($response->getBody());
}

现在你的解析器:

class ApiDtoParser
{
    public static function fromDto($raw)
    {
        $returnArray=[];
        $decoded =json_decode($data,true);
        foreach($decoded as $one){
            $obj = new DtoObj;
            foreach ($one as $key => $value) {
                $meth = "set". ucfirst(strtolower($key));
                $obj->{$meth}($var);
            }
            $returnArray[]=$obj;
        }
        return $returnArray;
    }
}

根据您摘录的上下文来判断,您需要创建基于请求的解析器

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读