doctorbeat / eloquent-repository
eloquent模型的存储库。使用它可以使模型看起来只有一个职责,从而使其可以独立进行单元测试
v1.0.2
2016-03-25 14:27 UTC
Requires
- php: >=5.3.2
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-14 16:18:58 UTC
README
eloquent模型的存储库。使用它可以使模型看起来只有一个职责,从而使其可以独立进行单元测试
安装
通过composer
require: "doctorbeat/eloquent-repository": "*"
为什么需要一个存储库?
Eloquent以其简洁性而著称,但这种简洁性使得Eloquent模型打破了“单一职责”原则。Eloquent模型既是实体(属性包)又处理数据库交互(选择、插入、更新、删除)。这使得您无法在隔离状态下模拟模型。您需要实体功能,但希望模拟数据库交互。
这一问题在Eloquent模型使用静态函数(如find()、all()和where())的事实中进一步体现。
这时出现了Eloquent Repository,它使您能够将模型作为实体/属性包使用,并将所有数据库交互方法移动到存储库中。存储库提供了一个可以模拟的接口。
方法和API
这些方法在存储库上可用,并且其API与相应的Eloquent方法相同
- 保存
- 删除
- 推送
- 触摸
- 所有
- 查找
- where*
- 所有其他静态方法
关系
要从存储库获取关系,请使用以下方法
[Model:] [Repository:] [result] - $model->parent $repo->getAttribute($model, 'parent'); the parent model - $model->children $repo->getAttribute($model, 'children'); the child models as a collection - $model->children() $repo->children($model); the child models as a relation - $model->children()->save($child) $repo->children($model, $child); add the child to the children of the model - $model->children()->saveMany($list) $repo->children($model, $list); add an array of new children to the children of the model
以下示例假设您已在模型上定义了父级和子级作为关系!
用法
$repo = new EloquentRepository('App\\Person'); $ent = new Person(); $ent->name = 'xyz'; $repo->save($ent); $repo->delete($ent); $all = $repo->all(); $person4 = $repo->find(4); $personXyz = $repo->whereName('xyz')->get();