php |动态 api 调用
php | dynamic api call
我正在尝试为我正在创建的 API 创建一个动态端点,以便包含一些数据,但前提是需要它,以便我可以在多个地方使用它。
我的想法是让 api.domain.com/vehicle
带回基本的车辆信息,但如果我这样做了 api.domain.com/vehicle?with=owners,history
那么我的想法是有一个函数映射 owners
和 history
到 class 将 return 数据,但仅在需要时。
这是我目前拥有的。
public static function vehicle()
{
$with = isset($_GET['with']) ? $_GET['with'] : null;
$properties = explode(',', $with);
$result = ['vehicle' => Vehicle::data($id)];
foreach ($properties as $property) {
array_push($result, static::getPropertyResponse($property));
}
echo json_encode($result);
}
然后会调用这个函数。
protected static function getPropertyResponse($property)
{
$propertyMap = [
'owners' => Vehicle::owner($id),
'history' => Vehicle::history($id)
];
if (array_key_exists($property, $propertyMap)) {
return $propertyMap[$property];
}
return null;
}
但是,我得到的响应嵌套在索引中,我不希望这样。我想要的格式是...
{
"vehicle": {
"make": "vehicle make"
},
"owners": {
"name": "owner name"
},
"history": {
"year": "26/01/2018"
}
}
但是我得到的格式是这样的...
{
"vehicle": {
"make": "vehicle make"
},
"0": {
"owners": {
"name": "owner name"
}
},
"1": {
"history": {
"year": "26/01/2018"
}
}
}
我该怎么做才不会 return 索引?
Vehicle::history($id)
似乎 return ['history'=>['year' => '26/01/2018']]
, ...等等
foreach ($properties as $property) {
$out = static::getPropertyResponse($property) ;
$result[$property] = $out[$property] ;
}
或者您的方法应该 return 类似于 ['year' => '26/01/2018']
并使用:
foreach ($properties as $property) {
$result[$property] = static::getPropertyResponse($property) ;
}
我正在尝试为我正在创建的 API 创建一个动态端点,以便包含一些数据,但前提是需要它,以便我可以在多个地方使用它。
我的想法是让 api.domain.com/vehicle
带回基本的车辆信息,但如果我这样做了 api.domain.com/vehicle?with=owners,history
那么我的想法是有一个函数映射 owners
和 history
到 class 将 return 数据,但仅在需要时。
这是我目前拥有的。
public static function vehicle()
{
$with = isset($_GET['with']) ? $_GET['with'] : null;
$properties = explode(',', $with);
$result = ['vehicle' => Vehicle::data($id)];
foreach ($properties as $property) {
array_push($result, static::getPropertyResponse($property));
}
echo json_encode($result);
}
然后会调用这个函数。
protected static function getPropertyResponse($property)
{
$propertyMap = [
'owners' => Vehicle::owner($id),
'history' => Vehicle::history($id)
];
if (array_key_exists($property, $propertyMap)) {
return $propertyMap[$property];
}
return null;
}
但是,我得到的响应嵌套在索引中,我不希望这样。我想要的格式是...
{
"vehicle": {
"make": "vehicle make"
},
"owners": {
"name": "owner name"
},
"history": {
"year": "26/01/2018"
}
}
但是我得到的格式是这样的...
{
"vehicle": {
"make": "vehicle make"
},
"0": {
"owners": {
"name": "owner name"
}
},
"1": {
"history": {
"year": "26/01/2018"
}
}
}
我该怎么做才不会 return 索引?
Vehicle::history($id)
似乎 return ['history'=>['year' => '26/01/2018']]
, ...等等
foreach ($properties as $property) {
$out = static::getPropertyResponse($property) ;
$result[$property] = $out[$property] ;
}
或者您的方法应该 return 类似于 ['year' => '26/01/2018']
并使用:
foreach ($properties as $property) {
$result[$property] = static::getPropertyResponse($property) ;
}