dan-har/presentit-laravel

用于嵌套Eloquent模型和集合的转换器,用于使用Laravel框架构建API

1.0.1 2017-07-04 17:58 UTC

This package is not auto-updated.

Last update: 2024-09-28 00:09:13 UTC


README

Presentit适配器,用于Laravel框架。

自定义嵌套Eloquent模型、模型关系和集合的展示和转换。

查看完整的presentit文档这里

文档

安装

使用composer安装

composer require dan-har/presentit-laravel

将presentit服务提供者添加到应用配置文件

'providers' => [
    // ...
    Presentit\Laravel\PresentitServiceProvider::class,
]

转换Eloquent模型

通过实现Presentable合约和使用PresentsItem特质,您可以使用presentit转换功能以任何Eloquent模型。

例如,具有PresentsItem特质的User模型类

class User extends Authenticatable implements Presentable
{
    use PresentsItem;
    
    //...
}

要转换用户模型,请使用present方法获取Present实例或使用transfrom方法使用转换器。

$user = User::find(1);

$user->present()->with(function(User $user){
    return [
        //...
    ];
});

$user->transform(function(User $user){
    return [
        //...
    ];
});

除了闭包转换器之外,您还可以传递转换器类,请参阅presentit文档或下面的示例。

转换集合

要转换集合,已添加到基本集合的presenttransformWith宏。

$posts = Collection::make();

$posts->present()->each(function (Post $post) {
    return [
        //...
    ];
});

$posts->transformWith(function (Post $post) {
    return [
        //...
    ];
});

返回集合的模型关系(如HasMany)也将具有presentit转换功能

集合presentit API使用transformWith方法,因为transform方法已存在于基本Laravel集合中。

class Post implements Presentable
{
    use PresentsItem;
    
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

$posts = Posts::find(1);

$posts->comments->transformWith(function (Comment $comment) {
    return [
        //...
    ];
});

转换嵌套模型和关系

为了展示嵌套模型转换,我们将使用一个包含评论的Post示例,每个评论中用户可以写入评论。因此,我们首先为Post、Comment和User模型使用转换器类

class UserTransformer
{
    public function transform(User $user) {
        return [
            'name' => ucfirst($user->name),
            'profile_image' => $user->profile_image ?: Hidden::key(),
        ];
    }
}


class CommentTransformer
{
    public function transform(Comment $comment)
    {
        return [
            'text' => $comment->text,
            'datetime' => $comment->created_at->toW3cString(),
            'edited_datetime' => $comment->edited_at ? $comment->edited_at : Hidden::key(),
            'user' => $comment->user->transform(UserTransformer::class),
            'comments' => $comment->comments->transformWith(CommentTransformer::class),
        ];
    }
}


class PostTransformer
{
    public function tranfrom(Post $post)
    {
        return [
            'title' => $post->title,
            'text' => $post->text,
            'user' => $post->user->transform(UserTransformer::class),
            'datetime' => $post->created_at->toW3cString(),
            'comments' => $post->comments->transformWith(CommentTransformer::class),
        ];
    }
}

然后要转换单个帖子,使用

$post = Post::find(1);

$array = $post->transform(PostTransformer::class)->show();