creolab / resources
处理资源集合和项的辅助类。
Requires
- illuminate/support: ~4
- nesbot/carbon: 1.*
Suggests
- creolab/image: dev-master
This package is auto-updated.
Last update: 2024-09-17 18:32:11 UTC
README
用于处理资源集合和项的简单辅助类
集合和项
基本集合类扩展了Laravel的集合类,这为我们提供了许多有用的方法。查看Laravel文档以了解具体有哪些可用。
新功能是可以将集合的每个项创建为项目类的新实例。默认情况下,这是该包内部的基本项目类,但您可以通过定义自己的集合和项,并简单地扩展此包中的项来覆盖它。
例如,可以是一个事件集合,因此我们会创建一个集合类
App\Resources\Collections\EventCollection
<?php namespace App\Resources\Collections;
class EventCollection extends \Creolab\Resources\Collection {
protected $item = '\App\Resources\Items\EventItem';
}
以及项类
App\Resources\Items\EventItem
<?php namespace App\Resources\Items;
class EventItem extends \Creolab\Resources\Item {
}
因此,每次我们创建一个新的用户集合时,它都会创建为
在您的项类中,您可以创建任何您喜欢的逻辑,因为它实际上表现得像某种展示器。您还可以像Eloquent模型一样使用自定义属性。所以如果您有一个具有
{{ $user->full_name }}
数据转换
由于我几乎为我的项目创建了所有仓库,因此我错过了一些Eloquent模型提供的功能,这正是创建此包的原因。假设我们有一个与之前类似的事件项,它有一些作为对象更有用的属性。这对于关系来说非常好。
因此,我们的项类现在看起来是这样的
App\Resources\Items\EventItem
<?php namespace App\Resources\Items;
class EventItem extends \Creolab\Resources\Item {
protected $transform = array(
'date' => 'date',
'from' => 'datetime',
'to' => 'datetime',
'author' => 'App\Resources\Items\UserItem',
'invitees' => 'App\Resources\Collections\UserCollection',
'attendees' => 'App\Resources\Collections\UserCollection',
'comments' => 'App\Resources\Collections\CommentCollection',
'mvp' => 'App\Resources\Items\UserItem',
);
}
如您所见,我们有一列需要“转换”的属性。日期、from和to属性变为Carbon\Carbon的实例,关系author、invitees、attendees和comments变为其他资源集合/项类的实例。所有这些都可以通过简单地创建EventItem类的新实例并传入一个数组来自动处理。这个数组可以通过Eloquent获取,因此事件仓库内部的查询看起来可能如下所示
App\Repositories\DbEventRepository.php
public function find($id, $options = null)
{
$event = Event::with(['author', 'invitees', 'attendees', 'mvp', 'comments.author'])
->where('id', $id)
->first();
return new EventItem($event->toArray());
}
转换目前没有很多功能,但您可以做的一件很酷的事情是图像处理。您必须安装creolab/image包以使其工作,并设置您的项类如下
App\Resources\Items\UserItem
<?php namespace App\Resources\Items;
class UserItem extends \Creolab\Resources\Item {
protected $transform = array(
'photo' => 'image',
);
}
photo属性将被转换为具有一些良好功能的图像对象。因此,您可以进行类似以下操作
<img src="{{ $user->photo->thumb(100) }}">
<img src="{{ $user->photo->resize(200, 100) }}">
就到这里了