nilportugues/eloquent-repository
Composer 安装命令:
composer require nilportugues/eloquent-repository
包简介
Eloquent Repository implementation
关键字:
README 文档
README
Eloquent Repository using nilportugues/repository as foundation.
Installation
Use Composer to install the package:
$ composer require nilportugues/eloquent-repository
Why? Drivers and Multiple Implementations!
Using this implementation you can switch it out to test your code without setting up databases.
Doesn't sound handy? Let's think of yet another use case you'll love using this. Functional tests and Unitary tests.
No database connection will be needed, nor fakes. Using an InMemoryRepository or FileSystemRepository implementation will make those a breeze to code. And once the tests finish, all data may be destroyed with no worries at all.
Available drivers:
Also, if you feel like changing the repository implementation, no logic changes would be needed, as there are a set of drivers for you to use out of the box:
composer require nilportugues/repository-cachefor caching.composer require nilportugues/repositoryfor an InMemoryRepository implementation.composer require nilportugues/filesystem-repositoryfor a FileSystemRepository implementation.composer require nilportugues/doctrine-repositoryfor a SQL Doctrine implementation.composer require nilportugues/eloquent-mongodb-repositoryfor a MongoDB Eloquent implementation.
Usage
To set up Eloquent you don't need Laravel or Lumen frameworks at all. This is how you use Eloquent in any project.
<?php use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule(); $capsule->addConnection( [ 'driver' => 'sqlite', 'database' => __DIR__.'/database.db', 'prefix' => '' ], 'default' //connection name. ); $capsule->bootEloquent(); $capsule->setAsGlobal();
Now that Eloquent is running, we can use the Repository.
One Repository for One Eloquent Model
A well defined repository returns one kind of objects that belong to one Business model.
<?php use NilPortugues\Foundation\Infrastructure\Model\Repository\Eloquent\EloquentRepository; class UserRepository extends EloquentRepository { /** * {@inheritdoc} */ protected function modelClassName() { return User::class; } }
To be faithful to the repository pattern, using Eloquent Models internally is OK, but Business objects should be returned.
Therefore, you should translate Eloquent to Business representations and the other way round. This is represented by $userAdapter in the example below.
The fully implementation should be along the lines:
<?php use NilPortugues\Foundation\Infrastructure\Model\Repository\Eloquent\EloquentRepository; class UserRepository extends EloquentRepository { protected $userAdapter; /** * @param $userAdapter */ public function __construct($userAdapter) { $this->userAdapter = $userAdapter; } /** * {@inheritdoc} */ protected function modelClassName() { return User::class; } /** * {@inheritdoc} */ public function find(Identity $id, Fields $fields = null) { $eloquentModel = parent::find($id, $fields); return $this->userAdapter->fromEloquent($eloquentModel); } /** * {@inheritdoc} */ public function findBy(Filter $filter = null, Sort $sort = null, Fields $fields = null) { $eloquentModelArray = parent::findBy($filter, $sort, $fields); return $this->fromEloquentArray($eloquentModelArray); } /** * {@inheritdoc} */ public function findAll(Pageable $pageable = null) { $page = parent::findAll($pageable); return new Page( $this->fromEloquentArray($page->content()), $page->totalElements(), $page->pageNumber(), $page->totalPages(), $page->sortings(), $page->filters(), $page->fields() ); } /** * @param array $eloquentModelArray * @return array */ protected function fromEloquentArray(array $eloquentModelArray) { $results = []; foreach ($eloquentModelArray as $eloquentModel) { //This is required to handle findAll returning array, not objects. $eloquentModel = (object) $eloquentModel; $results[] = $this->userAdapter->fromEloquent($eloquentModel); } return $results; } }
A sample implementation can be found in the /example directory.
One EloquentRepository for All Eloquent Models
While this is not the recommended way, as a repository should only return one kind of Business objects, this works well with Laravel projects.
While the amount of core is less than the previous example, bare in mind that your code will be coupled with Eloquent.
<?php use NilPortugues\Foundation\Infrastructure\Model\Repository\Eloquent\EloquentRepository as Repository; class EloquentRepository extends Repository { /** * @var string */ protected $modelClass; /** * @param string $modelClass */ public function __construct($modelClass) { $this->modelClass = (string) $modelClass; } /** * {@inheritdoc} */ protected function modelClassName() { return $this->modelClass; } }
Filtering data
Filtering is as simple as using the Filter object. For instance, lets retrieve how many users are named Ken.
<?php use NilPortugues\Foundation\Domain\Model\Repository\Filter; $repository = new UserRepository(); $filter = new Filter(); $filter->must()->contain('name', 'Ken'); echo $repository->count($filter);
Notice how the key name matches the database column name in the users table.
Available options
Filter allow you to use must(), mustNot() and should() methods to set up a fine-grained search. These provide a fluent interface with the following methods available:
public function notEmpty($filterName)public function hasEmpty($filterName)public function startsWith($filterName, $value)public function endsWith($filterName, $value)public function equal($filterName, $value)public function notEqual($filterName, $value)public function includeGroup($filterName, array $value)public function notIncludeGroup($filterName, array $value)public function range($filterName, $firstValue, $secondValue)public function notRange($filterName, $firstValue, $secondValue)public function notContain($filterName, $value)public function contain($filterName, $value)public function beGreaterThanOrEqual($filterName, $value)public function beGreaterThan($filterName, $value)public function beLessThanOrEqual($filterName, $value)public function beLessThan($filterName, $value)
Sorting data
Sorting is straight forward. Create an instance of Sort and pass in the column names and ordering.
<?php use NilPortugues\Foundation\Domain\Model\Repository\Sort; $repository = new UserRepository(); $filter = null; //all records $sort = new Sort(['name', 'id'], new Order('ASC', 'DESC')); $fields = null; //all columns $results = $repository->findBy($filter, $sort, $fields);
Fields data
Create a Fields object to fetch only selected columns. If no Fields object is passed, all columns are selected by default.
<?php use NilPortugues\Foundation\Domain\Model\Repository\Contracts\Fields; $repository = new UserRepository(); $filter = null; //all records $sort = null; //existing order $fields = new Fields(['name', 'id']); $results = $repository->findBy($filter, $sort, $fields);
Fetching data
Repository allows you to fetch data from the database by using the following methods:
public function findAll(Pageable $pageable = null)public function find(Identity $id, Fields $fields = null)public function findBy(Filter $filter = null, Sort $sort = null, Fields $fields = null)
Quality
To run the PHPUnit tests at the command line, go to the tests directory and issue phpunit.
This library attempts to comply with PSR-1, PSR-2, PSR-4.
If you notice compliance oversights, please send a patch via Pull Request.
Contribute
Contributions to the package are always welcome!
- Report any bugs or issues you find on the issue tracker.
- You can grab the source code at the package's Git Repository.
Support
Get in touch with me using one of the following means:
- Emailing me at contact@nilportugues.com
- Opening an Issue
Authors
License
The code base is licensed under the MIT license.
nilportugues/eloquent-repository 适用场景与选型建议
nilportugues/eloquent-repository 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 207 次下载、GitHub Stars 达 17, 最近一次更新时间为 2016 年 02 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「cache」 「repository」 「pagination」 「laravel」 「ddd」 「eloquent」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 nilportugues/eloquent-repository 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 nilportugues/eloquent-repository 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 nilportugues/eloquent-repository 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
repository php library
Laravel 5 - Repositories to the database layer
Provides a Data Grid tables for your Symfony project.
Structure for the Laravel Service-Repository Pattern
Normalize an index range from user input
Rinvex Repository is a simple, intuitive, and smart implementation of Active Repository with extremely flexible & granular caching system for Laravel, used to abstract the data layer, making applications more flexible to maintain.
统计信息
- 总下载量: 207
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 17
- 点击次数: 15
- 依赖项目数: 0
- 推荐数: 1
其他信息
- 授权协议: MIT
- 更新时间: 2016-02-10