Laravel5.5+ 使用API Resources快速输出自定义JSON方法详解


Posted in PHP onApril 06, 2020

从Laravel 5.5+开始,加入了API Resources这个概念。

我们先来看一下官网如何定义这个概念的:

When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.

可能看完这个概念之后,你仍然有点不明白,毕竟这个定义说的有点含糊。

如果你熟悉使用API进行输出,构架前后端分离的网络应用,那么你应该会发现,当我们使用Eloquent从数据库中取出数据后,如果想以JSON格式进行输出,那么我们可以使用->toJson()这个方法,这个方法可以直接将我们的model序列化(这个方法从Laravel 5.1+开始就可以使用了):

$user = App\User::find(1);

return $user->toJson();

使用多了,我们会发现,在model较为复杂,或者model中有很多我们API输出可能用不到的字段的情况下,toJson()仍然会忠实地帮我们把这些字段序列化出来。

这个时候,我们会想,如何将model中的某些字段隐藏起来,不输出到JSON中。另外一种情况,比如字段是password等一些敏感信息的时候,我们不希望JSON数据里包含这样的敏感信息。

要解决这个问题,我们可以在model里定义$hidden或者$visible这两个数组来进行字段的隐藏或者显示:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  /**
   * 不希望在序列化中出现的字段放入该数组中
   * 
   * @var array
   */
  protected $hidden = ['password', 'some', 'secret'];
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  /**
   * 只有在以下数组中出现的字段会被序列化
   *
   * @var array
   */
  protected $visible = ['first_name', 'last_name'];
}

那么你可能会想,我们已经有了可以自动序列化的方法,以及可以隐藏或者显示指定字段的方法,这样不就足够了吗?

现在我们来假设一个简单的应用场景。假设我们在输出一个客户列表,里面包含了客户名字和送货地址。我们使用Customer这个model定义客户,使用ShippingAddress这个model进行定义送货地址。为了简化场景,我们的客户只有一个送货地址,所以只会出现一一对应的情况。

那么在ShippingAddress对应的数据库表shipping_addresses中,我们可能会有如下定义:

| id | country_id | province_id | city_id | address |

字段类型我就不赘述了,其中country_id、province_id以及city_id这三个外键分别对应了国家、省份以及城市表中的id。

而Customer对应的customers表中,会有shipping_address_id这个外键指向shipping_addresses表中的id。

那么我们要输出顾客和送货地址,我们需要先在model中定义好relationship:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
  public function shippingAddress()
  {
    return $this->belongsTo(ShippingAddress::class);
  }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ShippingAddress extends Model
{
  public function country()
  {
    return $this->belongsTo(Country::class);
  }
  
  public function province()
  {
    return $this->belongsTo(Province::class);
  }
  
  public function city()
  {
    return $this->belongsTo(City::class);
  }
}

在我们的控制器中,我们拉取出所有客户:

<?php

namespace App\Http\Controllers;

use App\Customer;
use App\Http\Controllers\Controller;

class CustomerController extends Controller
{
  /**
   * Simple function to fetch all customers with their shipping addresses
   *
   * @return String
   */
  public function index()
  {
    $customers = Customer::with(['shippingAddress', 'shippingAddress.country', 'shippingAddress.province', 'shippingAddress.city'])->get();
    
    //这里可以直接返回Eloquent Collections或Objects,toJson()将自动被调用
    return $customers;
  }
}

那么输出的JSON将会包含了多个层级的关系,那么在我们前端调用的时候,将会非常麻烦,因为我们需要一层一层剥开Object关系。

但是如果你熟悉Laravel,你可能会说,慢着!这个情况我可以用accessor不就完事儿了吗?

是的,我们确实可以使用accessor来简化我们的数据层级:

/**
 * Get the customer's full shipping address
 *
 * @return string
 */
public function getFullShippingAddressAttribute()
{
  return "{$this->shippingAddress->country->name} {$this->shippingAddress->province->name} {$this->shippingAddress->city->name} {$this->shippingAddress->address}";
}

但是我们还需要一步操作。由于customers这张表本身没有full_shipping_address这个字段,要使我们的JSON输出包含full_shipping_address,我们需要添加$appends数组:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
  /**
   * The accessors to append to the model's array form.
   *
   * @var array
   */
  protected $appends = ['full_shipping_address'];
}

对于每一个我们想自定义的JSON字段,我们都需要进行上面两部的操作。这样一来其实非常麻烦,并且不利于代码的维护,因为这会让原本简洁的model显得很复杂。

基于以上原因,我们需要一个中间层,在我们输出model成为JSON的时候,可以进行一次信息的过滤及加工。

那么还是使用我们上面的应用场景。要输出自定义的字段再简单不过了。我们不需要在model里定义各种accessor,也不需要使用黑白名单过滤字段,只需要新建一个Resource类:

$ php artisan make:resource Customer

然后我们可以看到,在app/Http文件夹下,多出了一个名为Resources文件夹下,其中含有一个名为Customer.php的文件:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Customer extends JsonResource
{
  /**
   * Transform the resource into an array.
   *
   * @param \Illuminate\Http\Request $request
   * @return array
   */
  public function toArray($request)
  {
    return parent::toArray($request);
  }
}

这里我们看到其中有且仅有一个名为toArray的方法。这就是我们要自定字段的地方:

public function toArray($request)
  {
    return [
      'fullName' => $this->first_name . $this->last_name,
      'fullShippingAddress'  => $this->shippingAddress->country->name . $this->shippingAddress->province->name . $this->shippingAddress->city->name . $this->shippingAddress->address,
    ];
  }

注意到,无论是fullName还是fullShippingAddress,都是不存在于customers表中的字段。

接着,我们只需要简单修改一下我们的控制器:

<?php

namespace App\Http\Controllers;

use App\Customer;
use App\Http\Resources\Customer as CustomerResource;
use App\Http\Controllers\Controller;

class CustomerController extends Controller
{
  /**
   * Simple function to fetch all customers with their shipping addresses
   *
   * @return String
   */
  public function index()
  {
    $customers = Customer::with(['shippingAddress', 'shippingAddress.country', 'shippingAddress.province', 'shippingAddress.city'])->get();
    
    //这里我们使用了新的Resource类
    return CustomerResource::collection($customers);
  }
}

这样就OK了!我们输出的JSON数据中,将会仅仅含有以上两个字段,即fullName和fullShippingAddress,非常干净,并且前端直接可用,不需要二次再加工。

唯一需要注意的是,这里由于我们拉取了多个Customer,所以我们用了每个Resource类都自带有的collection方法,将一个Collection中的所有对象都进行处理。而若要处理单个对象,我们需要使用以下代码:

public function show($id)
{
  $customer = Customer::findOrFail($id);
  return new CustomerResource($customer);
}

要了解更多关于API Resources的详情,请戳官网文档:

https://laravel.com/docs/5.7/eloquent-resources

本文主要讲解了Laravel5.5+ 使用API Resources快速输出自定义JSON方法详解,更多关于Laravel框架的使用技巧请查看下面的相关链接

PHP 相关文章推荐
php类
Nov 27 PHP
坏狼的PHP学习教程之第1天
Jun 15 PHP
php chr() ord()中文截取乱码问题解决方法
Sep 08 PHP
PHP错误Cannot use object of type stdClass as array in错误的解决办法
Jun 12 PHP
PHP程序员常见的40个陋习,你中了几个?
Nov 20 PHP
PHP过滤黑名单关键字的方法
Dec 01 PHP
基于laravel制作APP接口(API)
Mar 15 PHP
php基于curl重写file_get_contents函数实例
Nov 08 PHP
thinkPHP自定义类实现方法详解
Nov 30 PHP
php判断str字符串是否是xml格式数据的方法示例
Jul 26 PHP
PHP连接MySQL数据库并以json格式输出
May 21 PHP
laravel框架路由分组,中间件,命名空间,子域名,路由前缀实例分析
Feb 18 PHP
Laravel 5+ .env环境配置文件详解
Apr 06 #PHP
Laravel5.3+框架定义API路径取消CSRF保护方法详解
Apr 06 #PHP
Laravel框架使用技巧之使用url()全局函数返回前一个页面的地址方法详解
Apr 06 #PHP
使用git迁移Laravel项目至新开发环境的步骤详解
Apr 06 #PHP
Laravel框架数据库迁移操作实例详解
Apr 06 #PHP
Laravel框架中队列和工作(Queues、Jobs)操作实例详解
Apr 06 #PHP
Laravel实现批量更新多条数据
Apr 06 #PHP
You might like
PHP页面中文乱码分析
2013/10/29 PHP
PHP实现原比例生成缩略图的方法
2016/02/03 PHP
ThinkPHP5.0框架实现切换数据库的方法分析
2019/10/30 PHP
jQuery Autocomplete自动完成插件
2010/07/17 Javascript
Array, Array Constructor, for in loop, typeof, instanceOf
2011/09/13 Javascript
jQuery元素选择器用法实例
2014/12/23 Javascript
js设置document.domain实现跨域的注意点分析
2015/05/21 Javascript
Node.js 数据加密传输浅析
2016/11/16 Javascript
H5实现中奖记录逐行滚动切换效果
2017/03/13 Javascript
angular2系列之路由转场动画的示例代码
2017/11/09 Javascript
Javascript防止图片拉伸的自适应处理方法
2017/12/26 Javascript
JavaScript中var、let、const区别浅析
2018/06/24 Javascript
使用webpack搭建vue项目及注意事项
2019/06/10 Javascript
微信小程序实现批量倒计时功能
2020/11/01 Javascript
vue 使用lodash实现对象数组深拷贝操作
2020/09/10 Javascript
vue keep-alive的简单总结
2021/01/25 Vue.js
python字符串编码识别模块chardet简单应用
2015/06/15 Python
简单了解python的内存管理机制
2019/07/08 Python
python实现静态服务器
2019/09/05 Python
python super用法及原理详解
2020/01/20 Python
Python爬取阿拉丁统计信息过程图解
2020/05/12 Python
Python Pandas 对列/行进行选择,增加,删除操作
2020/05/17 Python
Python的Tqdm模块实现进度条配置
2021/02/24 Python
GAP阿联酋官网:GAP UAE
2017/11/30 全球购物
Tuckernuck官网:经典的美国品质服装、鞋子和配饰
2021/01/11 全球购物
EMPHASIS艾斐诗官网:周生生旗下原创精品珠宝品牌
2020/12/17 全球购物
PHP两种查询函数array/row的区别
2013/06/03 面试题
在浏览器端如何得到服务器端响应的XML数据
2012/11/24 面试题
文明宿舍获奖感言
2014/02/07 职场文书
2014年消防工作实施方案
2014/02/20 职场文书
学校献爱心活动总结
2014/07/08 职场文书
领导班子对照检查材料
2014/09/22 职场文书
庆七一宣传标语
2014/10/08 职场文书
2015年路政工作总结
2015/05/22 职场文书
2016年“5.12”国际护士节活动总结
2016/04/06 职场文书
USB TYPE-C 或将成为所有智能手机充电标准
2022/04/21 数码科技