是否有一种从Dingo API响应中删除“数据”信封的简单方法。
当我使用此转换器转换用户模型时:
class UserTransformer extends EloquentModelTransformer
{
/**
* List of resources possible to include
*
* @var array
*/
protected $availableIncludes = [
'roles'
];
protected $defaultIncludes = [
'roles'
];
public function transform($model)
{
if(! $model instanceof User)
throw new InvalidArgumentException($model);
return [
'id' => $model->id,
'name' => $model->name,
'email' => $model->email
];
}
/**
* Include Roles
*
* @param User $user
* @return \League\Fractal\Resource\Item
*/
public function includeRoles(User $user)
{
$roles = $user->roles;
return $this->collection($roles, new RoleTransformer());
}我得到了这样的回应:
{
data : [
"id": 102,
"name": "Simo",
"email": "mail@outlook.com",
"roles": {
"data": [
{
"id": 1
"name": "admin"
}
]
}
}
]
}我读过一些关于HTTP的文章,其中很多文章都指出,这种封装的响应并不是很现代(您应该使用RESTful头)。
我如何禁用这种行为,至少包括在内?
谢谢
发布于 2016-02-24 13:08:39
对于那些后来开始学习它的人,由于我真的很难做到,我想分享一下我是如何让它在我的API中工作的:
1)创建自定义序列化程序,NoDataArraySerializer.php:
namespace App\Api\V1\Serializers;
use League\Fractal\Serializer\ArraySerializer;
class NoDataArraySerializer extends ArraySerializer
{
/**
* Serialize a collection.
*/
public function collection($resourceKey, array $data)
{
return ($resourceKey) ? [ $resourceKey => $data ] : $data;
}
/**
* Serialize an item.
*/
public function item($resourceKey, array $data)
{
return ($resourceKey) ? [ $resourceKey => $data ] : $data;
}
}2)设置新的序列化程序。在bootstrap/app.php中添加:
$app['Dingo\Api\Transformer\Factory']->setAdapter(function ($app) {
$fractal = new League\Fractal\Manager;
$fractal->setSerializer(new App\Api\V1\Serializers\NoDataArraySerializer);
return new Dingo\Api\Transformer\Adapter\Fractal($fractal);
});就这样。
现在,在您的UserController中(例如),您可以这样使用它:
namespace App\Api\V1\Controllers;
use App\Api\V1\Models\User;
use App\Api\V1\Transformers\UserTransformer;
class UserController extends Controller
{
public function index()
{
$items = User::all();
return $this->response->collection($items, new UserTransformer());
}
}其反应将是:
[
{
"user_id": 1,
...
},
{
"user_id": 2,
...
}
]或者,如果要添加信封,只需在Controller中设置资源键即可。取代:
return $this->response->collection($items, new UserTransformer());通过
return $this->response->collection($items, new UserTransformer(), ['key' => 'users']);其反应将是:
{
"users": [
{
"user_id": 1,
...
},
{
"user_id": 2,
...
}
]
}发布于 2017-07-28 20:20:20
加入了YouHieng的解决方案。在Laravel5.3和更高版本中注册NoDataArraySerializer的首选方法是编写自定义ServiceProvider,并将逻辑添加到boot()方法中,而不是bootstrap/app.php文件中。
例如:
php artisan make:provider DingoSerializerProvider然后:
public function boot(){
$this->app['Dingo\Api\Transformer\Factory']->setAdapter(function ($app) {
$fractal = new League\Fractal\Manager;
$fractal->setSerializer(new App\Http\Serializers\NoDataArraySerializer());
return new Dingo\Api\Transformer\Adapter\Fractal($fractal);
});
}发布于 2016-01-19 07:59:58
看看http://fractal.thephpleague.com/serializers/#arrayserializer。他们会解释什么时候该做什么
有时,人们希望删除项的“数据”命名空间。
https://stackoverflow.com/questions/33454645
复制相似问题