简体   繁体   English

翻译 PHP REST API 中的响应和请求

[英]translate response and request in PHP REST API

I am still struggling with a logic how to translate correctly the response and the request for my PHP REST API.我仍在努力解决如何正确翻译响应和对我的 PHP REST API 的请求的逻辑。 I have following array which I get from the REST API我有以下数组,我从 REST API 获得

[{
  "id": "49557a36-028b-40c6-b2d8-8095468af130",
  "startDate": "2020-04-15T06:00:00Z",
  "endDate": "2020-04-15T10:00:00Z",
  "bookedOn": "0001-01-01T00:00:00",
  "doctorNotes": "",
  "firstVisit": true,
  "visitReasonID": "",
  "patient": {
    "firstName": "",
    "lastName": "",
    "birthday": "0001-01-01T00:00:00",
    "gender": "x",
    "street": "",
    "postboxNumber": "",
    "city": "",
    "zip": "",
    "country": "",
    "email": "",
    "telephone": "",
    "info": ""
  }]

on the other hand I also have some data which I send to the REST API and it goes like this另一方面,我也有一些数据发送到 REST API,它是这样的

array(8) {
  ["GUID"]=>
  NULL
  ["datumzeit_from"]=>
  string(19) "2020-03-13 13:30:00"
  ["datumzeit_till"]=>
  string(16) "2020/03/13 17:00"
  ["titel"]=>
  string(2) "61"
  ["beschreibung"]=>
  string(4) "okay"
  ["firstVisit"]=>
  bool(true)
  ["patient"]=>
  array(1) {
    [0]=>
    array(11) {
      ["vorname"]=>
      string(4) "John"
      ["nachname"]=>
      string(7) "Daniels"
      ["geburtsdatum"]=>
      string(10) "1970-01-01"
      ["titel"]=>
      string(4) "Herr"
      ["strasse"]=>
      string(15) "Danielstraße 3"
      ["ort"]=>
      string(6) "Conan"
      ["plz"]=>
      string(5) "93085"
      ["land"]=>
      string(2) "DE"
      ["email"]=>
      string(1) "1"
      ["telnr"]=>
      string(10) "0835597839"
      ["referenz"]=>
      string(3) "nothing"
    }
  }
  ["last_updated"]=>
  string(19) "2020-03-09 17:08:23"
}

for proper translation I created an exchange Array which goes like this:为了正确翻译,我创建了一个如下所示的交换数组:

<?php $exchangeArray = array( 
    "id" => "GUID",
    "startDate" => "datumzeit_from",
    "endDate" => "datumzeit_till", 
    "bookedOn" => "last_updated", 
    "doctorNotes" => "beschreibung",
    "firstVisit" => "firstVisit",
    //"visitReasonName" => "titel",
    "visitReasonID" => "visitreason_nr",
    "patient" => array(
        "firstName" => "vorname",
        "lastName" => "nachname",
        "birthday" => "geburtsdatum",
        "gender" => "titel", //anders
        "street" => "strasse",
        //"postboxnumber" => "",
        "city" => "ort", // ort id
        "zip" => "plz",
        "country" => "land", 
        "email" => "email",
        "telephone" => "telnr",
        "info" => "referenz"),
); ?>

now to my main problem, always when I send or want to receive the data, I always want to translate it between my database and REST API and I do exactly the following $result = translate(json_decode($data, "IN"); //either json_decode+IN or encode+OUT to call the result I either put some data and send it out or decode and receive it. So I basically want to change keys and preserve the values, so here's the bottleneck现在到我的主要问题,总是当我发送或想要接收数据时,我总是想在我的数据库和 REST API 之间转换它,我完全按照以下$result = translate(json_decode($data, "IN"); //either json_decode+IN or encode+OUT调用结果我要么放一些数据然后发送出去,要么解码并接收它。所以我基本上想改变键并保留值,所以这里是瓶颈

function sortVars($var, $iterKey, $iterVal, $i, $IN = TRUE){ //the main logic is here and also the issue in the algorithm, it sorts out the variables
    if(is_array($var)){
        foreach($iterVal as $x=>$y){
            if($IN == TRUE){
                if(isset($var[$x])) $transformed[$i][$iterKey][$var[$x]] = $y;
            } else if(isset($var[$y])) $transformed[$i][$iterKey][$var[$y]] = $x;   
        }
    } else $transformed[$i][$var] = $iterVal;
return $transformed;
}   
function transSort($data, $stat, $i=0){ //that one sorts out the whole array
    global $exchangeArray;
    if($stat == "IN"){
        foreach($data as $kay=>$val){
            if(isset($exchangeArray[$kay])){
                $transformed[] = sortVars($exchangeArray[$kay], $kay, $val, $i);
            }       
        }
    } elseif($stat == "OUT"){
        foreach($exchangeArray as $kay=>$val){
            if(!is_array($val)){
                if(isset($data[$val])) $transformed = sortVars($data[$val], $val, $kay, $i, FALSE);
            } else{ //for strange reason its array with 0 in the beginning
                if(isset($data[0][$val])) $transformed = sortVars($data[$val], $val, $kay, $i, FALSE);
            }
        }
    }
    $i++;
    return $transformed;
}
function translate($data, $stat){ //translate response
    $i=0;
    if(isset($data[1])){ //if its array
        foreach($data as $key){
            $result = transSort($key, $stat, $i++);
        }
    } else $result = transSort($data, $stat);

    return $result;
}

It loops over arrays and depending on $stat translates them either to request or response, but it doesn't translate correctly and still has many issues, I had just one function before and $stat=IN worked perfectly fine but once I created more functions to have less code it started to have issues and also $stat=OUT has some logic problems regarding the correct translation, does someone have an idea what's the main issue in the following code?它在 arrays 上循环,并根据$stat将它们转换为请求或响应,但它不能正确转换并且仍然存在许多问题,我之前只有一个 function 和$stat=IN工作得很好但是一旦我创建了更多函数为了减少代码,它开始出现问题,并且$stat=OUT在正确翻译方面也存在一些逻辑问题,有人知道以下代码中的主要问题是什么吗?

I often run into cases where I need to convert something from model A to model B (regardless of translation).我经常遇到需要将某些内容从 model A 转换为 model B 的情况(无论翻译如何)。

I find that it's almost always easier to not create a configuration + system for automatically translating.我发现创建用于自动翻译的配置+系统几乎总是更容易。 Even though it's a bit more typing, just creating a function for each case has some advantages:尽管打字要多一些,但为每种情况创建一个 function 也有一些优势:

  1. Easier to see whats going on更容易看到发生了什么
  2. Simpler code更简单的代码
  3. Not every conversion is easy to express.并非每一次转换都容易表达。 This might make your 'conversion system' to grow in complexity over time and this can get very painful.这可能会使您的“转换系统”随着时间的推移变得越来越复杂,这可能会变得非常痛苦。 The configuration might at some point rival if you just wrote the code.如果您只是编写代码,配置可能会在某些时候与之竞争。 As you can see, it's already quite complex and hard to debug.如您所见,它已经相当复杂且难以调试。

So if this was me, I would write small conversion functions for each case:所以如果这是我,我会为每种情况编写小的转换函数:

function toGerman($input) {

  return [
    "datumzeit_from" => $input['startDate'],
    // every other property
  ];

}

I noticed that writing a function instead of a configuration + mapping system goes against the nature of a lot of devs, but it's easy to see how much easier and flexible this can be.我注意到编写 function 而不是配置 + 映射系统与许多开发人员的本性背道而驰,但很容易看出这可以变得多么容易和灵活。 It's just PHP.它只是 PHP。 You can use loops and deal with weird edge cases, Instead.相反,您可以使用循环并处理奇怪的边缘情况。 you wrote a little transpiler.你写了一个小转译器。

Unfortunately you might not consider this a real answer to your question, if so I'm happy to delete this answer.不幸的是,您可能不会认为这是您问题的真正答案,如果是这样,我很乐意删除此答案。

I think there is a slightly simpler way我认为有一个稍微简单的方法

1) Create a function to flip the German => Eng to Eng => German 1) 创建一个 function 翻转德语 => Eng 到 Eng => German

function array_flip_recursive($array) {

    $out = [];

    foreach ($array as $k => $v) {

        if (is_array($v)) {

            $out[$k] = array_flip_recursive($v);

        } else {

            $out[$v] = $k;

        }

    }

    return $out;

}

2) Replace the keys with the translated version 2)用翻译版本替换密钥

function translate($data, $dictionary, $flip = false) {

    if ($flip) $dictionary = array_flip_recursive($dictionary);

    $out = [];

    foreach ($data as $k => $v) {

        if (is_array($v)) {

            $out[$k] = translate($v, $dictionary[$k], $flip);

        } else {

            $out[$dictionary[$k]] = $v;

        }

    }

    return $out;

}

This function would take either your database output or the api output and the $exchangeArray from your earlier code.此 function 将使用您的数据库 output 或 api Z78E6221F6393D1356DZ681DB3 从您的早期代码中获取$exchangeArray Z78E6221F6393D1356DZ681DB3。 The $flip variable is in case you're converting German back to English. $flip变量用于将德语转换回英语。

Note you will need to json_decode($api_output, true) your API output to convert it to an associative array.请注意,您需要json_decode($api_output, true)您的 API output 将其转换为关联数组。 The example you gave was an array of data, so you'd then need to loop over it:你给出的例子是一个数据数组,所以你需要循环它:

3) Process your data 3) 处理您的数据

//From the API
foreach(json_decode($api_output, true) as $api_data) {

    $myData[] = translate($api_data, $exchangeArray);

}

print_r($myData);

//From your database
foreach($database_output as $database_data) {

     $myData[] = translate($database_data, $exchangeArray, true);

}

print_r($myData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM