如何将第三方 API 数据转换为 Laravel 5.6 中的集合资源?
How do you convert third party API data to a collection resource in Laravel 5.6?
我一直致力于为我们的各种 Web 应用程序创建一个干净的界面,但我 运行 遇到了麻烦 Laravel 的 API 资源无法正确转换将 json 数组传入 laravel 集合。
我可以用一个资源来完成:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
use App\Product;
class ProductResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->resource['product']['name'],
'description' => $this->resource['product']['description'],
'price' => $this->resource['product']['rental_rate']['price']
];
//return parent::toArray($request);
}
}
打印此响应输出:
{"name":"Arri Skypanel S60-C","description":"Arri Sky Panel S60-C 450w input with a 2000w tungsten equivalent & Combo Stand","price":"260.0"}
但是,尝试将这个单个项目变成一个项目集合不会有任何进展。
有人知道我遗漏了什么吗?
拉取 API 数据如下所示:
namespace App;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
class ThirPartyAPI
{
private $url = 'https://api.third-party.com/api/v1/';
public function pull($query, $additionalParams) {
$client = new Client;
$result = $client->get($this->url . $query . $additionalParams, [
'headers' => [
'Content-Type' => 'application/json',
'X-AUTH-TOKEN' => env('CURRENT-AUTH-TOKEN'),
'X-SUBDOMAIN' => env('CURRENT-SUBDOMAIN')
]
]);
$array = json_decode($result->getBody()->getContents(), true);
return $array;
}
}
API return 很多 json 数据。
这是产品型号:
public function getAllProducts() {
try {
$productData = [];
$query = "/products?page=1&per_page=3&filtermode=active";
$additionalParams = "";
$productData = new ThirdPartyAPI;
$productData = $productData->pull($query, $additionalParams);
$productData = $productData['products'];
return ProductsResource::make($productData);
} catch (\Exception $ex) {
return $ex;
} catch (\Throwable $ex) {
return $ex;
}
}
现在我正在尝试将所有 returned 数组转换成我可以控制更多的东西:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class ProductsResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'products' => $this->collection->mapInto(function($request) {
return[ 'name' => $this->resource['name'],
'description' => $this->resource['description'],
'price' => $this->resource['rental_rate']['price']
];
})
];
}
然而 var_dumping 数据只是 return 是这样的:
object(App\Http\Resources\ProductsResource)[200]
public 'resource' =>
array (size=3)
0 =>
array (size=37)
'id' => int 164
'name' => string '10A Dimmer' (length=10)
[Lots of data]
...
'sale_rates' =>
array (size=0)
...
1 => .....
[cont]
public 'with' =>
array (size=0)
empty
public 'additional' =>
array (size=0)
empty
我已经在 return json 信息上尝试了各种形式的数据转换,但除了错误和混乱的业务之外没有太多结果。我不太了解 Laravel 如何处理 API 资源处理。
好的,在对 Laravel 的 'make'、'mapinto' 和 'map' 集合方法进行一些调查之后,我最终从这里的转换中得到了一个工作结果:
$productData = ThirdPartyAPI;
$productData = $productData->pull($query, $additionalParams);
$productData = $productData['products'];
$products = collect($productData)->map(function($row){
return ProductsResource::make($row)->resolve();
});
var_dump($products);
那个var_dumpreturns这个:
object(Illuminate\Support\Collection)[228]
protected 'items' =>
array (size=3)
0 =>
array (size=3)
'name' => string '10A Dimmer' (length=10)
'description' => string '10amp Dimmer (Max 2.4k)' (length=23)
'price' => string '5.0' (length=3)
....
[And so on]
返回的初始信息是一个多维数组。
$returnedArray = array(
['array' => 1, 'name' => 'name', etc],
['array' => 2, 'name' => 'name, etc]
);
Laravel默认的集合方式只是把最上面的数组变成集合。为了能够通过资源模型正确控制结果,我们必须将整个数组集转换为集合,这意味着我们必须遍历返回的数据以将其转换为 laravel 可以正确读取的内容。这就是 map 方法的作用。
根据docs吧,'The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items'
make 方法创建一个新的集合实例。除了 docs 提到它 'resolves a given class or interface name to its instance using the service container' 之外,我不知道 resolve 函数的作用。我假设这意味着它确保正确地通过 class?
无论如何,我希望将来能对人们有所帮助。
我一直致力于为我们的各种 Web 应用程序创建一个干净的界面,但我 运行 遇到了麻烦 Laravel 的 API 资源无法正确转换将 json 数组传入 laravel 集合。
我可以用一个资源来完成:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
use App\Product;
class ProductResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->resource['product']['name'],
'description' => $this->resource['product']['description'],
'price' => $this->resource['product']['rental_rate']['price']
];
//return parent::toArray($request);
}
}
打印此响应输出:
{"name":"Arri Skypanel S60-C","description":"Arri Sky Panel S60-C 450w input with a 2000w tungsten equivalent & Combo Stand","price":"260.0"}
但是,尝试将这个单个项目变成一个项目集合不会有任何进展。
有人知道我遗漏了什么吗?
拉取 API 数据如下所示:
namespace App;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
class ThirPartyAPI
{
private $url = 'https://api.third-party.com/api/v1/';
public function pull($query, $additionalParams) {
$client = new Client;
$result = $client->get($this->url . $query . $additionalParams, [
'headers' => [
'Content-Type' => 'application/json',
'X-AUTH-TOKEN' => env('CURRENT-AUTH-TOKEN'),
'X-SUBDOMAIN' => env('CURRENT-SUBDOMAIN')
]
]);
$array = json_decode($result->getBody()->getContents(), true);
return $array;
}
}
API return 很多 json 数据。
这是产品型号:
public function getAllProducts() {
try {
$productData = [];
$query = "/products?page=1&per_page=3&filtermode=active";
$additionalParams = "";
$productData = new ThirdPartyAPI;
$productData = $productData->pull($query, $additionalParams);
$productData = $productData['products'];
return ProductsResource::make($productData);
} catch (\Exception $ex) {
return $ex;
} catch (\Throwable $ex) {
return $ex;
}
}
现在我正在尝试将所有 returned 数组转换成我可以控制更多的东西:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class ProductsResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'products' => $this->collection->mapInto(function($request) {
return[ 'name' => $this->resource['name'],
'description' => $this->resource['description'],
'price' => $this->resource['rental_rate']['price']
];
})
];
}
然而 var_dumping 数据只是 return 是这样的:
object(App\Http\Resources\ProductsResource)[200]
public 'resource' =>
array (size=3)
0 =>
array (size=37)
'id' => int 164
'name' => string '10A Dimmer' (length=10)
[Lots of data]
...
'sale_rates' =>
array (size=0)
...
1 => .....
[cont]
public 'with' =>
array (size=0)
empty
public 'additional' =>
array (size=0)
empty
我已经在 return json 信息上尝试了各种形式的数据转换,但除了错误和混乱的业务之外没有太多结果。我不太了解 Laravel 如何处理 API 资源处理。
好的,在对 Laravel 的 'make'、'mapinto' 和 'map' 集合方法进行一些调查之后,我最终从这里的转换中得到了一个工作结果:
$productData = ThirdPartyAPI;
$productData = $productData->pull($query, $additionalParams);
$productData = $productData['products'];
$products = collect($productData)->map(function($row){
return ProductsResource::make($row)->resolve();
});
var_dump($products);
那个var_dumpreturns这个:
object(Illuminate\Support\Collection)[228]
protected 'items' =>
array (size=3)
0 =>
array (size=3)
'name' => string '10A Dimmer' (length=10)
'description' => string '10amp Dimmer (Max 2.4k)' (length=23)
'price' => string '5.0' (length=3)
....
[And so on]
返回的初始信息是一个多维数组。
$returnedArray = array(
['array' => 1, 'name' => 'name', etc],
['array' => 2, 'name' => 'name, etc]
);
Laravel默认的集合方式只是把最上面的数组变成集合。为了能够通过资源模型正确控制结果,我们必须将整个数组集转换为集合,这意味着我们必须遍历返回的数据以将其转换为 laravel 可以正确读取的内容。这就是 map 方法的作用。
根据docs吧,'The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items'
make 方法创建一个新的集合实例。除了 docs 提到它 'resolves a given class or interface name to its instance using the service container' 之外,我不知道 resolve 函数的作用。我假设这意味着它确保正确地通过 class?
无论如何,我希望将来能对人们有所帮助。