默认情况下,对于所有API,我都是从laravel分形库获取数据作为对象的。
我不想要数据,而是想要一些自定义名称而不是数据,但是我无法做到这一点。
如何自定义分形库中的代码以获取项目而不是数据。
答案 0 :(得分:0)
创建DataSerializer
类:
namespace App\{Your Project Name}\Serializers;
use League\Fractal\Serializer\ArraySerializer;
class DataSerializer extends ArraySerializer
{
public function collection($resourceKey, array $data)
{
if ($resourceKey) {
return [$resourceKey => $data];
}
return $data;
}
public function item($resourceKey, array $data)
{
if ($resourceKey) {
return [$resourceKey => $data];
}
return $data;
}
}
在基本控制器中添加setResponseData
函数:
public function setResponseData($default=true, $data, $transformer, $includes = null){
if($default){
$resource = fractal($data, $transformer);
if($includes){
$resource->parseIncludes($includes);
}
return $resource;
}
$resource = null;
if($data instanceof LengthAwarePaginator){
$dataCollection = $data->getCollection();
$resource = new Collection($dataCollection, $transformer, 'data');
$resource->setPaginator(new IlluminatePaginatorAdapter($data));
} elseif($data instanceof \Illuminate\Database\Eloquent\Collection){
$resource = new Collection($data, $transformer, 'data');
} elseif($data instanceof Model){
$resource = new Item($data, $transformer, 'data');
} else{
return [];
}
$manager = new Manager();
$manager->setSerializer(new DataSerializer());
if($includes){
$manager->parseIncludes($includes);
}
$content = [];
if($resource){
$content = $manager->createData($resource)->toArray();
}
return $content;
}
从派生控制器中调用setResponseData
函数:
$response = $this->setResponseData(false, $data, new YourTransformer(), ['include-1']);