presenter的概念

顾名思义,presenter的原意就是呈现,展现。在这里,它就是一个包装器和呈现器。其主要作用就是将从repository中查询出来的数据将要返回(呈现)给前端时进行重新包装

使用场景

当我们的Api接口要隐藏不需要的字段时,通过在transfomer中重新设置模型要返回的字段,然后通过presentertransformer转换器(一个或多个)进行包裹后再将数据返回给前端,而无须修改模型本身的属性。从而实现MVC模型中M层和V层的松耦合。

使用

安装fractal(一般不需要此步骤,可跳过)

composer require league/fractal

注意:fractal一般在安装I5-repository时已经安装好了,该扩展是用于数据转换的,即:transfomer,若之前安装过dingo/api的话,也是自带该依赖的。

创建 Tramsformer

php artisan make:transformer UserResource

命令生成的transformer类:

<?php

namespace App\Transformers;

use App\Models\UserResource;
use League\Fractal\TransformerAbstract;

/**
 * Class UserResourceTransformer.
 *
 * @package namespace App\Transformers;
 */
class UserResourceTransformer extends TransformerAbstract
{
    protected $availableIncludes = ['user'];

    /**
     * Transform the UserResource entity.
     *
     * @param \App\Models\UserResource $model
     *
     * @return array
     */
    public function transform(UserResource $model)
    {

    }

}

transform方法中重新设置要返回的字段:

    public function transform(UserResource $model)
    {
        return [
            'id'            => $model->id,
            'title'         => $model->title,
            'recmnd_goods'  => $model->recmnd_goods,
            'content'       => $model->content,
            'imgs'          => $model->imgs,
        ];
    }

使用命令创建Presenter呈现器

php artisan make:presenter UserResource
<?php

namespace App\Repositories\Presenters;

use App\Transformers\UserResourceTransformer;
use Prettus\Repository\Presenter\FractalPresenter;

/**
 * Class UserResourcePresenter.
 *
 * @package namespace App\Repositories\Presenters;
 */
class UserResourcePresenter extends FractalPresenter
{
    /**
     * Transformer
     *
     * @return \League\Fractal\TransformerAbstract
     */
    public function getTransformer()
    {
        return new UserResourceTransformer();
    }
}

在控制器中使用presenter呈现器

<?php

namespace App\Http\Controllers\Api;

use App\Repositories\Presenters\UserResourcePresenter;
use App\Repositories\Interfaces\UserResourceRepository;
use App\Validators\UserResourceValidator;

/**
 * Class UserResourcesController.
 *
 * @package namespace App\Http\Controllers\Api;
 */
class UserResourcesController extends CommonController
{
    /**
     * @var UserResourceRepository
     */
    protected $repository;

    /**
     * @var UserResourceValidator
     */
    protected $validator;

    /**
     * UserResourcesController constructor.
     *
     * @param UserResourceRepository $repository
     * @param UserResourceValidator $validator
     */
    public function __construct(UserResourceRepository $repository, UserResourceValidator $validator)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
        $this->repository->setPresenter(UserResourcePresenter::class);
        $userResources = $this->repository->all();

        return response()->json($userResources);
    }

    
}

接口返回结果:

{
    "data": [
        {
            "id": 1,
            "title": "糖尿病人的饮食规划1",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ]
        },
        {
            "id": 2,
            "title": "糖尿病人的饮食规划2",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ]
        },
        {
            "id": 3,
            "title": "糖尿病人的饮食规划3",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ]
        },
        {
            "id": 4,
            "title": "糖尿病人的饮食规划4",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ]
        },
        {
            "id": 39,
            "title": "糖尿病人的饮食规划",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ]
        },
        {
            "id": 40,
            "title": "糖尿病人的饮食规划",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ]
        },
        {
            "id": 41,
            "title": "糖尿病人的饮食规划",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ]
        }
    ]
}

返回关联数据

大多数情况下,接口返回的肯定不止一个模型的数据,我们需要返回更多关联模型的数据,此时,在transfomer转换器中设置$availableIncludes属性并定义相对应的方法即可。

比如,在返回的userResource数据中要同时带上资源关联的user数据,我们设置$availableIncludes['user'],同时创建includeUser方法,如下所示:

<?php

namespace App\Transformers;

use App\Models\UserResource;
use League\Fractal\TransformerAbstract;

/**
 * Class UserResourceTransformer.
 *
 * @package namespace App\Transformers;
 */
class UserResourceTransformer extends TransformerAbstract
{
    protected $availableIncludes = ['user'];

    /**
     * Transform the UserResource entity.
     *
     * @param \App\Models\UserResource $model
     *
     * @return array
     */
    public function transform(UserResource $model)
    {
        return [
            'id'            => $model->id,
            'title'         => $model->title,
            'recmnd_goods'  => $model->recmnd_goods,
            'content'       => $model->content,
            'imgs'          => $model->imgs,
        ];
    }

    public function includeUser(UserResource $model)
    {
        $user = $model->user;
        return $this->item($user, new UserTransformer());
    }
}

上面,既然设置了关联user数据,那么就要在UserRessource模型中设置user关联:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

/**
 * Class UserResource.
 *
 * @package namespace App\Models;
 */
class UserResource extends Model implements Transformable
{
    use TransformableTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'type',
        'content',
        'imgs',
    ];

    /**
     * 关联用户
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this -> belongsTo(User::class,'user_id');
    }
}

在请求路由上加上请求参数include=user

{
    "data": [
        {
            "id": 1,
            "title": "糖尿病人的饮食规划1",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ],
            "user": {
                "data": {
                    "id": 1,
                    "nickname": "wample-1"
                }
            }
        },
        {
            "id": 2,
            "title": "糖尿病人的饮食规划2",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ],
            "user": {
                "data": {
                    "id": 1,
                    "nickname": "wample-1"
                }
            }
        },
        {
            "id": 3,
            "title": "糖尿病人的饮食规划3",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ],
            "user": {
                "data": {
                    "id": 1,
                    "nickname": "wample-1"
                }
            }
        },
        {
            "id": 4,
            "title": "糖尿病人的饮食规划4",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ],
            "user": {
                "data": {
                    "id": 1,
                    "nickname": "wample-1"
                }
            }
        },
        {
            "id": 39,
            "title": "糖尿病人的饮食规划",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ],
            "user": {
                "data": {
                    "id": 1,
                    "nickname": "wample-1"
                }
            }
        },
        {
            "id": 40,
            "title": "糖尿病人的饮食规划",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ],
            "user": {
                "data": {
                    "id": 1,
                    "nickname": "wample-1"
                }
            }
        },
        {
            "id": 41,
            "title": "糖尿病人的饮食规划",
            "recmnd_goods": "",
            "content": "对糖尿病人来说,如莜麦面、荞麦面、燕麦片、玉米面、紫山药等富含维生素B、多种微量元素及食物纤维,以低糖,低淀粉的食物或者粗粮以及蔬菜等做主食。豆类及豆制品,豆类食品富含蛋白质、无机盐和维生素,且豆油含不饱和脂肪酸,能降低血清胆固醇及甘油三酯。苦瓜、桑叶、洋葱、香菇、柚子、南瓜可降低血糖,是糖尿病人最理想食物,如能长期食用,则降血糖和预防并发症的效果会更好。",
            "imgs": [
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/m8iq2GMxJcW0jba4bEx3ehHmdqdFoqqrn3HzwghC.png",
                "https://shiyiguan.oss-cn-beijing.aliyuncs.com/image/9Grcl2LWvYHc8IyCYr7DR1ZH4jaM3zjwcLsbDJ7q.jpeg"
            ],
            "user": {
                "data": {
                    "id": 1,
                    "nickname": "wample-1"
                }
            }
        }
    ]
}

wample
12 声望1 粉丝

引用和评论

0 条评论