prettus / l5-repository
Laravel 5|6|7|8|9|10|11 - 数据库层仓库
Requires
- illuminate/config: ~5.0|~6.0|~7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/console: ~5.0|~6.0|~7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/database: ~5.0|~6.0|~7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/filesystem: ~5.0|~6.0|~7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/http: ~5.0|~6.0|~7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/pagination: ~5.0|~6.0|~7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/support: ~5.0|~6.0|~7.0|^8.0|^9.0|^10.0|^11.0
- illuminate/validation: ~5.0|~6.0|~7.0|^8.0|^9.0|^10.0|^11.0
- prettus/laravel-validation: ~1.1|~1.2|~1.3|~1.4|~1.5|~1.6
Suggests
- league/fractal: Required to use the Fractal Presenter (0.12.*).
- prettus/laravel-validation: Required to provide easy validation with the repository (1.1.*)
- robclancy/presenter: Required to use the Presenter Model (1.3.*)
- dev-master
- 2.9.1
- 2.9.0
- 2.8.0
- 2.7.9
- 2.7.8
- 2.7.7
- 2.7.6
- 2.7.5
- 2.7.4
- 2.7.3
- 2.7.2
- 2.7.1
- 2.7.0
- 2.6.46
- 2.6.45
- 2.6.44
- 2.6.43
- 2.6.42
- 2.6.41
- 2.6.40
- 2.6.39
- 2.6.38
- 2.6.37
- 2.6.36
- 2.6.35
- 2.6.34
- 2.6.33
- 2.6.32
- 2.6.31
- 2.6.30
- 2.6.29
- 2.6.28
- 2.6.27
- 2.6.26
- 2.6.25
- 2.6.24
- 2.6.23
- 2.6.22
- 2.6.21
- 2.6.20
- 2.6.19
- 2.6.18
- 2.6.17
- 2.6.16
- 2.6.15
- 2.6.14
- 2.6.13
- 2.6.12
- 2.6.11
- 2.6.10
- 2.6.9
- 2.6.8
- 2.6.7
- 2.6.6
- 2.6.5
- 2.6.4
- 2.6.3
- 2.6.2
- 2.6.1
- 2.5.1
- 2.5.0
- 2.4.0
- 2.3.0
- 2.2.4
- 2.2.3
- 2.2.2
- 2.2.1
- 2.2.0
- 2.1.8
- 2.1.7
- 2.1.6
- 2.1.5
- 2.1.4
- 2.1.3
- 2.1.2
- 2.1.1
- 2.1.0
- 2.0.14
- 2.0.13
- 2.0.12
- 2.0.11
- 2.0.10
- 2.0.9
- 2.0.8
- 2.0.7
- 2.0.6
- 2.0.5
- 2.0.4
- 2.0.3
- 2.0.2
- 2.0.1
- 2.0.0
- 1.0.4
- 1.0.3
- 1.0.2
- 1.0.1
- 1.0.0
- dev-between_filter
- dev-orderby_new_features
- dev-addInCondition
- dev-bsormagec-patch-1
- dev-develop
- dev-3.0-develop
This package is auto-updated.
Last update: 2024-09-06 15:16:36 UTC
README
Laravel 5 Repositories用于抽象数据层,使我们的应用程序更易于维护。
查看版本:1.0.* / 2.0.*
迁移到:2.0 / 2.1
想了解更多关于仓库模式的信息? 阅读这篇文章。
目录
安装
Composer
执行以下命令以获取软件包的最新版本
composer require prettus/l5-repository
Laravel
>= laravel5.5
ServiceProvider将自动附加
其他
在你的config/app.php
中将Prettus\Repository\Providers\RepositoryServiceProvider::class
添加到providers
数组的末尾
'providers' => [ ... Prettus\Repository\Providers\RepositoryServiceProvider::class, ],
如果是Lumen
$app->register(Prettus\Repository\Providers\LumenRepositoryServiceProvider::class);
发布配置
php artisan vendor:publish --provider "Prettus\Repository\Providers\RepositoryServiceProvider"
方法
Prettus\Repository\Contracts\RepositoryInterface
- all($columns = array('*'))
- first($columns = array('*'))
- paginate($limit = null, $columns = ['*'])
- find($id, $columns = ['*'])
- findByField($field, $value, $columns = ['*'])
- findWhere(array $where, $columns = ['*'])
- findWhereIn($field, array $where, $columns = [*])
- findWhereNotIn($field, array $where, $columns = [*])
- findWhereBetween($field, array $where, $columns = [*])
- create(array $attributes)
- update(array $attributes, $id)
- updateOrCreate(array $attributes, array $values = [])
- delete($id)
- deleteWhere(array $where)
- orderBy($column, $direction = 'asc');
- with(array $relations);
- has(string $relation);
- whereHas(string $relation, closure $closure);
- hidden(array $fields);
- visible(array $fields);
- scopeQuery(Closure $scope);
- getFieldsSearchable();
- setPresenter($presenter);
- skipPresenter($status = true);
Prettus\Repository\Contracts\RepositoryCriteriaInterface
- pushCriteria($criteria)
- popCriteria($criteria)
- getCriteria()
- getByCriteria(CriteriaInterface $criteria)
- skipCriteria($status = true)
- getFieldsSearchable()
Prettus\Repository\Contracts\CacheableInterface
- setCacheRepository(CacheRepository $repository)
- getCacheRepository()
- getCacheKey($method, $args = null)
- getCacheTime()
- skipCache($status = true)
Prettus\Repository\Contracts\PresenterInterface
- present($data);
Prettus\Repository\Contracts\Presentable
- setPresenter(PresenterInterface $presenter);
- presenter();
Prettus\Repository\Contracts\CriteriaInterface
- apply($model, RepositoryInterface $repository);
Prettus\Repository\Contracts\Transformable
- transform();
使用
创建模型
正常创建您的模型,但定义可以从输入表单数据填充的属性非常重要。
namespace App; class Post extends Eloquent { // or Ardent, Or any other Model Class protected $fillable = [ 'title', 'author', ... ]; ... }
创建仓库
namespace App; use Prettus\Repository\Eloquent\BaseRepository; class PostRepository extends BaseRepository { /** * Specify Model class name * * @return string */ function model() { return "App\\Post"; } }
生成器
通过生成器轻松创建您的存储库。
配置
您必须首先配置存储库文件的存储位置。默认情况下是 "app" 文件夹和命名空间 "App"。请注意,paths
数组中的值实际上用作 命名空间 和文件路径。不过,生成时已处理前后斜杠。
... 'generator'=>[ 'basePath'=>app()->path(), 'rootNamespace'=>'App\\', 'paths'=>[ 'models' => 'Entities', 'repositories' => 'Repositories', 'interfaces' => 'Repositories', 'transformers' => 'Transformers', 'presenters' => 'Presenters', 'validators' => 'Validators', 'controllers' => 'Http/Controllers', 'provider' => 'RepositoryServiceProvider', 'criteria' => 'Criteria', ] ]
您可能希望将项目文件夹的根目录放在 "app" 之外并添加另一个命名空间,例如
... 'generator'=>[ 'basePath' => base_path('src/Lorem'), 'rootNamespace' => 'Lorem\\' ]
此外,您可能希望自定义生成类保存的位置。这可以通过编辑 paths
节点来实现。例如
'generator'=>[ 'basePath'=>app()->path(), 'rootNamespace'=>'App\\', 'paths'=>[ 'models'=>'Models', 'repositories'=>'Repositories\\Eloquent', 'interfaces'=>'Contracts\\Repositories', 'transformers'=>'Transformers', 'presenters'=>'Presenters' 'validators' => 'Validators', 'controllers' => 'Http/Controllers', 'provider' => 'RepositoryServiceProvider', 'criteria' => 'Criteria', ] ]
命令
要生成您模型所需的所有内容,请运行此命令
php artisan make:entity Post
这将创建控制器、验证器、模型、存储库、演示者(Presenter)和转换器类。它还将创建一个新的服务提供者,用于将 Eloquent 存储库与其对应的存储库接口绑定。要加载它,只需将其添加到 AppServiceProvider 的 @register 方法中
$this->app->register(RepositoryServiceProvider::class);
您也可以传递来自 repository
命令的选项,因为此命令只是一个包装器。
要为您的 Post 模型生成存储库,请使用以下命令
php artisan make:repository Post
要为具有 Blog 命名空间的 Post 模型生成存储库,请使用以下命令
php artisan make:repository "Blog\Post"
添加可填充字段
php artisan make:repository "Blog\Post" --fillable="title,content"
要直接使用命令添加验证规则,需要传递 --rules
选项并创建迁移
php artisan make:entity Cat --fillable="title:string,content:text" --rules="title=>required|min:2, content=>sometimes|min:10"
此命令还将创建您的基本 RESTful 控制器,因此只需将此行添加到 routes.php
文件中,您将获得基本的 CRUD。
Route::resource('cats', CatsController::class);
运行命令时,您将在您设置的默认文件夹中创建 "Entities" 文件夹和 "Repositories"。
现在完成了,您仍然需要将其实际存储库的接口绑定,例如在您自己的 Repositories Service Provider 中。
App::bind('{YOUR_NAMESPACE}Repositories\PostRepository', '{YOUR_NAMESPACE}Repositories\PostRepositoryEloquent');
并使用
public function __construct({YOUR_NAMESPACE}Repositories\PostRepository $repository){ $this->repository = $repository; }
或者,您可以使用 artisan 命令为您完成绑定。
php artisan make:bindings Cats
使用方法
namespace App\Http\Controllers; use App\PostRepository; class PostsController extends BaseController { /** * @var PostRepository */ protected $repository; public function __construct(PostRepository $repository){ $this->repository = $repository; } .... }
在存储库中查找所有结果
$posts = $this->repository->all();
在存储库中按分页查找所有结果
$posts = $this->repository->paginate($limit = null, $columns = ['*']);
按 id 查找结果
$post = $this->repository->find($id);
隐藏模型的属性
$post = $this->repository->hidden(['country_id'])->find($id);
只显示模型的具体属性
$post = $this->repository->visible(['id', 'state_id'])->find($id);
加载模型关系
$post = $this->repository->with(['state'])->find($id);
按字段名查找结果
$posts = $this->repository->findByField('country_id','15');
按多个字段查找结果
$posts = $this->repository->findWhere([ //Default Condition = 'state_id'=>'10', 'country_id'=>'15', //Custom Condition ['columnName1','>','10'], //DATE, DAY, MONTH, YEAR ['columnName2','DATE','2021-07-02'], //whereDate ['columnName3','DATE >=','2021-07-02'], //whereDate with operator ['columnName4','IN',['value1','value2']], //whereIn ['columnName5','NOTIN',['value1','value2']], //whereNotIn ['columnName6','EXIST',''], //whereExists //HAS, HASMORPH, DOESNTHAVE, DOESNTHAVEMORPH ['columnName7','HAS',function($query){}], //whereHas //BETWEEN, BETWEENCOLUMNS, NOTBETWEEN, NOTBETWEENCOLUMNS ['columnName8','BETWEEN',[10, 100]], //whereBetween ]);
按一个字段中的多个值查找结果
$posts = $this->repository->findWhereIn('id', [1,2,3,4,5]);
按一个字段中排除多个值查找结果
$posts = $this->repository->findWhereNotIn('id', [6,7,8,9,10]);
使用自定义作用域查找所有结果
$posts = $this->repository->scopeQuery(function($query){ return $query->orderBy('sort_order','asc'); })->all();
在存储库中创建新条目
$post = $this->repository->create( Input::all() );
更新存储库中的条目
$post = $this->repository->update( Input::all(), $id );
在存储库中删除条目
$this->repository->delete($id)
按多个字段删除存储库中的条目
$this->repository->deleteWhere([ //Default Condition = 'state_id'=>'10', 'country_id'=>'15', ])
创建条件
使用命令
php artisan make:criteria MyCriteria
标准是更改查询存储库的一种方式,通过根据您的需求应用特定条件。您可以在您的存储库中添加多个标准。
use Prettus\Repository\Contracts\RepositoryInterface; use Prettus\Repository\Contracts\CriteriaInterface; class MyCriteria implements CriteriaInterface { public function apply($model, RepositoryInterface $repository) { $model = $model->where('user_id','=', Auth::user()->id ); return $model; } }
在控制器中使用条件
namespace App\Http\Controllers; use App\PostRepository; class PostsController extends BaseController { /** * @var PostRepository */ protected $repository; public function __construct(PostRepository $repository){ $this->repository = $repository; } public function index() { $this->repository->pushCriteria(new MyCriteria1()); $this->repository->pushCriteria(MyCriteria2::class); $posts = $this->repository->all(); ... } }
从标准获取结果
$posts = $this->repository->getByCriteria(new MyCriteria());
设置存储库中的默认标准
use Prettus\Repository\Eloquent\BaseRepository; class PostRepository extends BaseRepository { public function boot(){ $this->pushCriteria(new MyCriteria()); // or $this->pushCriteria(AnotherCriteria::class); ... } function model(){ return "App\\Post"; } }
跳过存储库中定义的标准
在使用任何其他链式方法之前使用 skipCriteria
$posts = $this->repository->skipCriteria()->all();
弹出标准
使用 popCriteria
来删除标准
$this->repository->popCriteria(new Criteria1()); // or $this->repository->popCriteria(Criteria1::class);
使用请求条件
RequestCriteria 是一个标准的标准实现。它允许从请求中发送的参数执行过滤器。
您可以执行动态搜索,过滤数据并自定义查询。
要在您的存储库中使用标准,您可以在存储库的 boot 方法中添加新的标准,或直接在控制器中使用,以过滤出少数请求。
在仓库中启用
use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Criteria\RequestCriteria; class PostRepository extends BaseRepository { /** * @var array */ protected $fieldSearchable = [ 'name', 'email' ]; public function boot(){ $this->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria')); ... } function model(){ return "App\\Post"; } }
记住,您需要定义模型中哪些字段可以被搜索。
在您的仓库中设置 $fieldSearchable,并指定可搜索的字段名称或字段关系。
protected $fieldSearchable = [ 'name', 'email', 'product.name' ];
您可以设置用于执行查询的条件类型,默认条件是 "="
protected $fieldSearchable = [ 'name'=>'like', 'email', // Default Condition "=" 'your_field'=>'condition' ];
在控制器中启用
public function index() { $this->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria')); $posts = $this->repository->all(); ... }
示例条件
通过请求请求所有数据,不进行筛选
http://prettus.local/users
[ { "id": 1, "name": "John Doe", "email": "[email protected]", "created_at": "-0001-11-30 00:00:00", "updated_at": "-0001-11-30 00:00:00" }, { "id": 2, "name": "Lorem Ipsum", "email": "[email protected]", "created_at": "-0001-11-30 00:00:00", "updated_at": "-0001-11-30 00:00:00" }, { "id": 3, "name": "Laravel", "email": "[email protected]", "created_at": "-0001-11-30 00:00:00", "updated_at": "-0001-11-30 00:00:00" } ]
在仓库中进行研究
http://prettus.local/users?search=John%20Doe
或
http://prettus.local/users?search=John&searchFields=name:like
或
http://prettus.local/[email protected]&searchFields=email:=
或
http://prettus.local/users?search=name:John Doe;email:[email protected]
或
http://prettus.local/users?search=name:John;email:[email protected]&searchFields=name:like;email:=
[ { "id": 1, "name": "John Doe", "email": "[email protected]", "created_at": "-0001-11-30 00:00:00", "updated_at": "-0001-11-30 00:00:00" } ]
您可以使用“search”参数而不是完整的“searchFields”参数。
http://prettus.local/users?search=id:2;age:17;email:[email protected]&searchFields='id':=
默认情况下,RequestCriteria使用每个查询参数的OR比较运算符进行查询。http://prettus.local/users?search=age:17;email:[email protected]
上面的示例将执行以下查询
SELECT * FROM users WHERE age = 17 OR email = '[email protected]';
为了使用AND进行查询,请传递如下所示的searchJoin参数
http://prettus.local/users?search=age:17;email:[email protected]&searchJoin=and
筛选字段
http://prettus.local/users?filter=id;name
[ { "id": 1, "name": "John Doe" }, { "id": 2, "name": "Lorem Ipsum" }, { "id": 3, "name": "Laravel" } ]
排序结果
http://prettus.local/users?filter=id;name&orderBy=id&sortedBy=desc
[ { "id": 3, "name": "Laravel" }, { "id": 2, "name": "Lorem Ipsum" }, { "id": 1, "name": "John Doe" } ]
通过相关表排序
http://prettus.local/users?orderBy=posts|title&sortedBy=desc
查询将如下所示
... INNER JOIN posts ON users.post_id = posts.id ... ORDER BY title ...
http://prettus.local/users?orderBy=posts:custom_id|posts.title&sortedBy=desc
查询将如下所示
... INNER JOIN posts ON users.custom_id = posts.id ... ORDER BY posts.title ...
http://prettus.local/users?orderBy=posts:custom_id,other_id|posts.title&sortedBy=desc
查询将如下所示
... INNER JOIN posts ON users.custom_id = posts.other_id ... ORDER BY posts.title ...
按相同排序方式排序多列
http://prettus.local/users?orderBy=name;created_at&sortedBy=desc
结果将如下所示
[ { "id": 1, "name": "Laravel", "created_at": "-0001-11-29 00:00:00" }, { "id": 3, "name": "Laravel", "created_at": "-0001-11-28 00:00:00" }, { "id": 2, "name": "John Doe", "created_at": "-0001-11-30 00:00:00" } ]
按不同排序方式排序多列
http://prettus.local/users?orderBy=name;created_at&sortedBy=desc;asc
结果将如下所示
[ { "id": 3, "name": "Laravel", "created_at": "-0001-11-28 00:00:00" }, { "id": 1, "name": "Laravel", "created_at": "-0001-11-29 00:00:00" }, { "id": 2, "name": "John Doe", "created_at": "-0001-11-30 00:00:00" } ]
添加关系
http://prettus.local/users?with=groups
之间筛选
http://prettus.local/product?search=price:100,500&searchFields=price:between
结果将如下所示
[ { "id": 3, "price": "150", "created_at": "-0001-11-28 00:00:00" }, { "id": 1, "price": "300", "created_at": "-0001-11-29 00:00:00" }, { "id": 2, "price": "450", "created_at": "-0001-11-30 00:00:00" } ]
WhereIn筛选
http://prettus.local/product?search=price:300,500&searchFields=price:in
结果将如下所示
[ { "id": 1, "price": "300", "created_at": "-0001-11-29 00:00:00" } ]
重写参数名称
您可以在配置文件 config/repository.php 中更改参数名称
缓存
轻松为您的仓库添加缓存层
缓存使用
实现CacheableInterface接口并使用CacheableRepository特性。
use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Contracts\CacheableInterface; use Prettus\Repository\Traits\CacheableRepository; class PostRepository extends BaseRepository implements CacheableInterface { use CacheableRepository; ... }
完成,这样您的仓库就会被缓存,并且在创建、修改或删除条目时清除仓库缓存。
缓存配置
您可以在文件 config/repository.php 中更改缓存设置,也可以直接在您的仓库上进行。
config/repository.php
'cache'=>[ //Enable or disable cache repositories 'enabled' => true, //Lifetime of cache 'minutes' => 30, //Repository Cache, implementation Illuminate\Contracts\Cache\Repository 'repository'=> 'cache', //Sets clearing the cache 'clean' => [ //Enable, disable clearing the cache on changes 'enabled' => true, 'on' => [ //Enable, disable clearing the cache when you create an item 'create'=>true, //Enable, disable clearing the cache when upgrading an item 'update'=>true, //Enable, disable clearing the cache when you delete an item 'delete'=>true, ] ], 'params' => [ //Request parameter that will be used to bypass the cache repository 'skipCache'=>'skipCache' ], 'allowed'=>[ //Allow caching only for some methods 'only' =>null, //Allow caching for all available methods, except 'except'=>null ], ],
您可以在仓库中直接覆盖这些设置。
use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Contracts\CacheableInterface; use Prettus\Repository\Traits\CacheableRepository; class PostRepository extends BaseRepository implements CacheableInterface { // Setting the lifetime of the cache to a repository specifically protected $cacheMinutes = 90; protected $cacheOnly = ['all', ...]; //or protected $cacheExcept = ['find', ...]; use CacheableRepository; ... }
缓存方法包括:all、paginate、find、findByField、findWhere、getByCriteria
验证器
需要 prettus/laravel-validator。 composer require prettus/laravel-validator
使用 prettus/laravel-validator
进行简单验证
使用验证器类
创建验证器
在下面的示例中,我们为创建和编辑定义了一些规则
use \Prettus\Validator\LaravelValidator; class PostValidator extends LaravelValidator { protected $rules = [ 'title' => 'required', 'text' => 'min:3', 'author'=> 'required' ]; }
要定义特定规则,请按照以下步骤进行
use \Prettus\Validator\Contracts\ValidatorInterface; use \Prettus\Validator\LaravelValidator; class PostValidator extends LaravelValidator { protected $rules = [ ValidatorInterface::RULE_CREATE => [ 'title' => 'required', 'text' => 'min:3', 'author'=> 'required' ], ValidatorInterface::RULE_UPDATE => [ 'title' => 'required' ] ]; }
在仓库中启用验证器
use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Criteria\RequestCriteria; class PostRepository extends BaseRepository { /** * Specify Model class name * * @return mixed */ function model(){ return "App\\Post"; } /** * Specify Validator class name * * @return mixed */ public function validator() { return "App\\PostValidator"; } }
在仓库中定义规则
或者,您可以直接在规则仓库属性中设置您的规则,而不是使用类来定义其验证规则,它将具有与验证类相同的效果。
use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Criteria\RequestCriteria; use Prettus\Validator\Contracts\ValidatorInterface; class PostRepository extends BaseRepository { /** * Specify Validator Rules * @var array */ protected $rules = [ ValidatorInterface::RULE_CREATE => [ 'title' => 'required', 'text' => 'min:3', 'author'=> 'required' ], ValidatorInterface::RULE_UPDATE => [ 'title' => 'required' ] ]; /** * Specify Model class name * * @return mixed */ function model(){ return "App\\Post"; } }
验证现在就绪。如果失败,将抛出类型为Prettus\Validator\Exceptions\ValidatorException的异常
展示器
展示者充当对象的包装器和渲染器。
Fractal 展示器
需要 Fractal。 composer require league/fractal
实现展示者有两种方式,第一种是创建一个TransformerAbstract并使用您的展示者类设置,如创建Transformer类中所述。
第二种方式是使您的模型实现Transformable接口,并使用默认的展示者ModelFractarPresenter,这将具有相同的效果。
转换器类
使用命令创建转换器
php artisan make:transformer Post
这将生成下面的类。
创建一个Transformer类
use League\Fractal\TransformerAbstract; class PostTransformer extends TransformerAbstract { public function transform(\Post $post) { return [ 'id' => (int) $post->id, 'title' => $post->title, 'content' => $post->content ]; } }
使用命令创建一个Presenter
php artisan make:presenter Post
如果你还没有创建Transformer,命令会提示你创建。
创建一个Presenter
use Prettus\Repository\Presenter\FractalPresenter; class PostPresenter extends FractalPresenter { /** * Prepare data to present * * @return \League\Fractal\TransformerAbstract */ public function getTransformer() { return new PostTransformer(); } }
在仓库中启用
use Prettus\Repository\Eloquent\BaseRepository; class PostRepository extends BaseRepository { ... public function presenter() { return "App\\Presenter\\PostPresenter"; } }
或者在控制器中启用它:
$this->repository->setPresenter("App\\Presenter\\PostPresenter");
从Model获取后使用Presenter
如果你记录了一个Presenter,有时使用了skipPresenter()
方法,或者你不想你的结果被Presenter自动更改。你可以在你的model上实现Presentable接口,这样你就可以在任何时候展示你的model。参见以下示例:
在你的model中实现接口Prettus\Repository\Contracts\Presentable
和Prettus\Repository\Traits\PresentableTrait
namespace App; use Prettus\Repository\Contracts\Presentable; use Prettus\Repository\Traits\PresentableTrait; class Post extends Eloquent implements Presentable { use PresentableTrait; protected $fillable = [ 'title', 'author', ... ]; ... }
现在你可以单独提交你的Model,看以下示例:
$repository = app('App\PostRepository'); $repository->setPresenter("Prettus\\Repository\\Presenter\\ModelFractalPresenter"); //Getting the result transformed by the presenter directly in the search $post = $repository->find(1); print_r( $post ); //It produces an output as array ... //Skip presenter and bringing the original result of the Model $post = $repository->skipPresenter()->find(1); print_r( $post ); //It produces an output as a Model object print_r( $post->presenter() ); //It produces an output as array
你可以在每次访问时跳过Presenter,并直接在model中使用它,为了这样做,在你的repository中将$skipPresenter
属性设置为true
use Prettus\Repository\Eloquent\BaseRepository; class PostRepository extends BaseRepository { /** * @var bool */ protected $skipPresenter = true; public function presenter() { return "App\\Presenter\\PostPresenter"; } }
Model类
实现接口
namespace App; use Prettus\Repository\Contracts\Transformable; class Post extends Eloquent implements Transformable { ... /** * @return array */ public function transform() { return [ 'id' => (int) $this->id, 'title' => $this->title, 'content' => $this->content ]; } }
在仓库中启用
Prettus\Repository\Presenter\ModelFractalPresenter
是对于实现Transformable的Model的默认Presenter
use Prettus\Repository\Eloquent\BaseRepository; class PostRepository extends BaseRepository { ... public function presenter() { return "Prettus\\Repository\\Presenter\\ModelFractalPresenter"; } }
或者在控制器中启用它:
$this->repository->setPresenter("Prettus\\Repository\\Presenter\\ModelFractalPresenter");
在repository中跳过定义的Presenter
在任何其他链式方法之前使用skipPresenter
$posts = $this->repository->skipPresenter()->all();
或
$this->repository->skipPresenter(); $posts = $this->repository->all();