Aje*_*esh 11 php transformer-model laravel dingo-api thephpleague-fractal
我一直在使用laravel来构建我的API.我使用变换器来转换模型对象的数据.
现在我没有数据库,而是来自API的响应作为数据源,我想将这些数据转换回用户,但我无法这样做.
我的控制器
public function rocByName(Request $request)
{
try {
$this->roc_by_name_validator->with( $request->all() )->passesOrFail();
$company_name = $request->input('company_name');
$result = $this->my_service->getDetailsByName($company_name); //$result has the response object from the API which I want to transform and give it as a response.
return $this->response->collection($result,new OnboardingTransformer()); //Tried using tranformer like this
}
catch (ValidatorException $e) {
dd($e);
}
}
Run Code Online (Sandbox Code Playgroud)
我的变形金刚
<?php
namespace Modules\Onboarding\Transformers;
use League\Fractal\TransformerAbstract;
use App\Entities\OnboardingEntity; //I dont have an entity since the response is coming from an API!! What will give here?
/**
* Class OnboardingTransformerTransformer
* @package namespace App\Transformers;
*/
class OnboardingTransformer extends TransformerAbstract
{
/**
* Transform the \OnboardingTransformer entity
* @param \OnboardingTransformer $model
*
* @return array
*/
public function transform(OnboardingEntity $data_source)
{
return [
'company_name' => $data_source->company_name,
];
}
}
Run Code Online (Sandbox Code Playgroud)
这里的OnboardingEntity是指理想地来自数据库的数据.这里我不是从数据库中获取数据,而是我的数据来自API源.我该怎么做呢 我在这里很少被灌输.有人可以给出解决方案吗?
$ result有以下响应
[
[
{
"companyID": "U72400MHTC293037",
"companyName": "pay pvt LIMITED"
},
{
"companyID": "U74900HR2016PT853",
"companyName": "dddd PRIVATE LIMITED"
}
]
]
Run Code Online (Sandbox Code Playgroud)
小智 2
$this->response->collection旨在获取对象的集合,而不是数组。然后所有这些对象都将根据需要进行转换,即转换 OnboardingEntity 对象。因此,首先您应该将输入数组转换为对象集合。我上面的示例是如何做到的(您应该将其更改为您自己的输入数组)
$data = json_decode('[
[
{
"companyID": "U72400MHTC293037",
"companyName": "pay pvt LIMITED"
},
{
"companyID": "U74900HR2016PT853",
"companyName": "dddd PRIVATE LIMITED"
}
]
]');
$data = collect( array_map( function($ob){
return (new OnboardingEntity($ob));
}, $data[0]));
Run Code Online (Sandbox Code Playgroud)
然后将 OnboardingEntity 对象的集合传递给$this->response->collection方法,如下所示
$this->response->collection($data,new TestTransformer());