从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的详情,请戳官网文档:

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