如果一个函数我们需要多次使用的话,我们就可以把它写成一个借口,这样每次使用的时候可以根据自己的需求写入自己的内容
先展示代码
1.定义
Transformer
接口
<?php
namespace App\Transformer;
abstract class Transformer
{
public function transformCollection($items)
{
return array_map([$this,'transform'],$items);
}
public abstract function transform($items);
}
2.实现接口的类
LessionTransformer
<?php
namespace App\LessionTransformer;
use App\Transformer\Transformer;
class LessionTransformer extends Transformer
{
public function transform($lession)
{
// TODO: Implement transform() method.
return [
'id' => $lession['id'],
'name' => $lession['name'],
'email' => $lession['email'],
];
}
}
我们需要展示id,name,email的时候,使用这个方法,如果需要展示其他字段,我们可以额外再写方法
- 具体使用的类
LessionController
<?php
namespace App\Http\Controllers;
use App\LessionTransformer\LessionTransformer;
use App\User;
class LessionController extends ApiController
{
protected $lessionTransformer;
public function __construct(LessionTransformer $lessionTranformer)
{
$this->lessionTransformer = $lessionTranformer;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$lession =User::all();
return \Response::json([
'status' => 'success',
'status_code' => 200,
//此处的lession变量需要转化为数组
'data' => $this->lessionTransformer->transformCollection($lession->toArray())
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$lession =User::findOrfail($id);
return \Response::json([
'status' => 'success',
'status_code' => 200,
'data' => $this->lessionTransformer->transform($lession)
]);
}
}
- 此处说下
API
字段的映射
public function test_map($lession)
{
return array_map(function($lession){
return [
'id' => $lession['id'],
'name' => $lession['name'],
'email' => $lession['email'],
];
},$lession->toArray());
}
// 如果获取的值是多组值,我们使用 tranformCollection
public function tranformCollection($lessions)
{
return array_map([$this,'tranform'],$lessions->toArray());
}
// 如果只有一组值,我们使用 tranform
public function tranform($lession)
{
return [
'id' => $lession['id'],
'name' => $lession['name'],
'email' => $lession['email'],
];
}