{"id":15664142,"url":"https://github.com/nilportugues/eloquent-repository","last_synced_at":"2025-05-06T18:50:04.146Z","repository":{"id":57027220,"uuid":"51262496","full_name":"nilportugues/eloquent-repository","owner":"nilportugues","description":"Eloquent Repository implementation","archived":false,"fork":false,"pushed_at":"2016-06-13T16:49:02.000Z","size":46,"stargazers_count":17,"open_issues_count":3,"forks_count":1,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-03-05T15:05:45.735Z","etag":null,"topics":["crud","database","dbal","eloquent","filter","illuminate","laravel","laravel5","mysql","orm","pageable","paginate","php","php7","sql","sqlite","storage"],"latest_commit_sha":null,"homepage":"http://nilportugues.com","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nilportugues.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-02-07T19:38:09.000Z","updated_at":"2022-02-12T06:55:00.000Z","dependencies_parsed_at":"2022-08-23T16:11:06.558Z","dependency_job_id":null,"html_url":"https://github.com/nilportugues/eloquent-repository","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Feloquent-repository","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Feloquent-repository/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Feloquent-repository/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Feloquent-repository/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nilportugues","download_url":"https://codeload.github.com/nilportugues/eloquent-repository/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252750285,"owners_count":21798684,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["crud","database","dbal","eloquent","filter","illuminate","laravel","laravel5","mysql","orm","pageable","paginate","php","php7","sql","sqlite","storage"],"created_at":"2024-10-03T13:41:25.890Z","updated_at":"2025-05-06T18:50:04.127Z","avatar_url":"https://github.com/nilportugues.png","language":"PHP","funding_links":["https://paypal.me/nilportugues"],"categories":[],"sub_categories":[],"readme":"# Eloquent Repository\n![PHP7 Tested](http://php-eye.com/badge/nilportugues/eloquent-repository/php70.svg)\n[![Build Status](https://travis-ci.org/PHPRepository/php-eloquent-repository.svg)](https://travis-ci.org/PHPRepository/php-eloquent-repository) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/nilportugues/php-eloquent-repository/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/nilportugues/php-eloquent-repository/?branch=master) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/8d362f15-8385-40c0-a7a6-672c857352b4/mini.png)](https://insight.sensiolabs.com/projects/8d362f15-8385-40c0-a7a6-672c857352b4) [![Latest Stable Version](https://poser.pugx.org/nilportugues/eloquent-repository/v/stable)](https://packagist.org/packages/nilportugues/eloquent-repository) [![Total Downloads](https://poser.pugx.org/nilportugues/eloquent-repository/downloads)](https://packagist.org/packages/nilportugues/eloquent-repository) [![License](https://poser.pugx.org/nilportugues/eloquent-repository/license)](https://packagist.org/packages/nilportugues/eloquent-repository)\n[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://paypal.me/nilportugues)\n\nEloquent Repository using *[nilportugues/repository](https://github.com/nilportugues/php-repository)* as foundation.\n\n## Installation\n\nUse [Composer](https://getcomposer.org) to install the package:\n\n```json\n$ composer require nilportugues/eloquent-repository\n```\n\n## Why? Drivers and Multiple Implementations!\n\nUsing this implementation you can switch it out to test your code without setting up databases.\n\nDoesn't sound handy? Let's think of yet another use case you'll love using this. `Functional tests` and `Unitary tests`.\n\nNo 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.\n\n**Available drivers:**\n\nAlso, 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:\n\n- `composer require nilportugues/repository-cache` for [caching](https://github.com/nilportugues/php-repository-cache).\n- `composer require nilportugues/repository` for an [InMemoryRepository implementation](https://github.com/nilportugues/php-repository).\n- `composer require nilportugues/filesystem-repository` for a [FileSystemRepository implementation](https://github.com/nilportugues/php-filesystem-repository).\n- `composer require nilportugues/doctrine-repository` for a [SQL Doctrine implementation](https://github.com/nilportugues/php-doctrine-repository).\n- `composer require nilportugues/eloquent-mongodb-repository` for a [MongoDB Eloquent implementation](https://github.com/nilportugues/php-eloquent-mongodb-repository).\n\n\n\n## Usage\n\nTo set up Eloquent you don't need Laravel or Lumen frameworks at all. This is how you use Eloquent in any project. \n\n```php\n\u003c?php\nuse Illuminate\\Database\\Capsule\\Manager as Capsule;\n\n$capsule = new Capsule();\n$capsule-\u003eaddConnection(\n    [\n        'driver' =\u003e 'sqlite', \n        'database' =\u003e __DIR__.'/database.db',\n        'prefix' =\u003e ''\n    ], \n    'default' //connection name.\n);\n$capsule-\u003ebootEloquent();\n$capsule-\u003esetAsGlobal();\n```\n\nNow that Eloquent is running, we can use the Repository.\n\n### One Repository for One Eloquent Model\n\nA well defined repository returns one kind of objects that belong to one Business model.\n\n```php\n\u003c?php\nuse NilPortugues\\Foundation\\Infrastructure\\Model\\Repository\\Eloquent\\EloquentRepository;\n\nclass UserRepository extends EloquentRepository \n{\n    /**\n     * {@inheritdoc}\n     */\n    protected function modelClassName()\n    {\n        return User::class;\n    }\n}\n```\n\nTo be faithful to the repository pattern, using Eloquent Models internally is OK, but Business objects should be returned. \n\nTherefore, you should translate Eloquent to Business representations and the other way round. This is represented by `$userAdapter` in the example below.\n\nThe fully implementation should be along the lines:\n\n```php\n\u003c?php\nuse NilPortugues\\Foundation\\Infrastructure\\Model\\Repository\\Eloquent\\EloquentRepository;\n\nclass UserRepository extends EloquentRepository \n{\n    protected $userAdapter;\n    \n    /**\n     * @param $userAdapter\n     */\n    public function __construct($userAdapter)\n    {\n        $this-\u003euserAdapter = $userAdapter; \n    }\n    \n    /**\n     * {@inheritdoc}\n     */\n    protected function modelClassName()\n    {\n        return User::class;\n    }\n    \n    /**\n     * {@inheritdoc}\n     */    \n    public function find(Identity $id, Fields $fields = null)\n    {\n        $eloquentModel = parent::find($id, $fields);   \n        \n        return $this-\u003euserAdapter-\u003efromEloquent($eloquentModel);\n    }\n    \n    /**\n     * {@inheritdoc}\n     */    \n    public function findBy(Filter $filter = null, Sort $sort = null, Fields $fields = null)\n    {\n        $eloquentModelArray = parent::findBy($filter, $sort, $fields);   \n        \n        return $this-\u003efromEloquentArray($eloquentModelArray);\n    }       \n    \n    /**\n     * {@inheritdoc}\n     */\n    public function findAll(Pageable $pageable = null)\n    {\n        $page = parent::findAll($pageable);\n        \n        return new Page(\n            $this-\u003efromEloquentArray($page-\u003econtent()),\n            $page-\u003etotalElements(),\n            $page-\u003epageNumber(),\n            $page-\u003etotalPages(),\n            $page-\u003esortings(),\n            $page-\u003efilters(),\n            $page-\u003efields()\n        );\n    } \n\n   /**\n    * @param array $eloquentModelArray\n    * @return array\n    */\n   protected function fromEloquentArray(array $eloquentModelArray)\n   {\n        $results = [];\n        foreach ($eloquentModelArray as $eloquentModel) {\n            //This is required to handle findAll returning array, not objects.\n            $eloquentModel = (object) $eloquentModel;\n            \n            $results[] = $this-\u003euserAdapter-\u003efromEloquent($eloquentModel);\n        }\n        \n        return $results;\n   } \n}\n```\n\nA sample implementation can be found in the [/example](https://github.com/nilportugues/php-eloquent-repository/tree/master/example) directory.\n\n### One EloquentRepository for All Eloquent Models\n\nWhile **this is not the recommended way**, as a repository should only return one kind of Business objects, this works well with Laravel projects.\n\nWhile the amount of core is less than the previous example, bare in mind that your code will be coupled with Eloquent.\n\n```php\n\u003c?php\nuse NilPortugues\\Foundation\\Infrastructure\\Model\\Repository\\Eloquent\\EloquentRepository as Repository;\n\nclass EloquentRepository extends Repository\n{\n    /**\n     * @var string\n     */\n    protected $modelClass;\n    \n    /**\n     * @param string $modelClass\n     */\n    public function __construct($modelClass)\n    {\n        $this-\u003emodelClass = (string) $modelClass;\n    }\n    \n    /**\n     * {@inheritdoc}\n     */\n    protected function modelClassName()\n    {\n        return $this-\u003emodelClass;\n    }\n}\n```\n\n## Filtering data\n\nFiltering is as simple as using the `Filter` object. For instance, lets retrieve how many users are named `Ken`. \n \n```php\n\u003c?php\nuse NilPortugues\\Foundation\\Domain\\Model\\Repository\\Filter;\n\n$repository = new UserRepository();\n\n$filter = new Filter();\n$filter-\u003emust()-\u003econtain('name', 'Ken');\n\necho $repository-\u003ecount($filter);\n```\n\nNotice how the key `name` matches the database column `name` in the `users` table.\n\n**Available options**\n\nFilter 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: \n    \n- `public function notEmpty($filterName)`\n- `public function hasEmpty($filterName)`\n- `public function startsWith($filterName, $value)`\n- `public function endsWith($filterName, $value)`\n- `public function equal($filterName, $value)`\n- `public function notEqual($filterName, $value)`\n- `public function includeGroup($filterName, array $value)`\n- `public function notIncludeGroup($filterName, array $value)`\n- `public function range($filterName, $firstValue, $secondValue)`\n- `public function notRange($filterName, $firstValue, $secondValue)`\n- `public function notContain($filterName, $value)`\n- `public function contain($filterName, $value)`\n- `public function beGreaterThanOrEqual($filterName, $value)`\n- `public function beGreaterThan($filterName, $value)`\n- `public function beLessThanOrEqual($filterName, $value)`\n- `public function beLessThan($filterName, $value)`\n    \n## Sorting data\n\nSorting is straight forward. Create an instance of Sort and pass in the column names and ordering.\n\n```php\n\u003c?php\nuse NilPortugues\\Foundation\\Domain\\Model\\Repository\\Sort;\n\n$repository = new UserRepository();\n\n$filter = null; //all records\n$sort = new Sort(['name', 'id'], new Order('ASC', 'DESC'));\n$fields = null; //all columns\n\n$results = $repository-\u003efindBy($filter, $sort, $fields);\n```\n\n## Fields data\n\nCreate a Fields object to fetch only selected columns. If no Fields object is passed, all columns are selected by default.\n\n```php\n\u003c?php\nuse NilPortugues\\Foundation\\Domain\\Model\\Repository\\Contracts\\Fields;\n\n$repository = new UserRepository();\n\n$filter = null; //all records\n$sort = null; //existing order\n$fields = new Fields(['name', 'id']);\n\n$results = $repository-\u003efindBy($filter, $sort, $fields);\n```\n\n## Fetching data\n\nRepository allows you to fetch data from the database by using the following methods:\n\n- `public function findAll(Pageable $pageable = null)`\n- `public function find(Identity $id, Fields $fields = null)`\n- `public function findBy(Filter $filter = null, Sort $sort = null, Fields $fields = null)`\n\n\n## Quality\n\nTo run the PHPUnit tests at the command line, go to the tests directory and issue phpunit.\n\nThis library attempts to comply with [PSR-1](http://www.php-fig.org/psr/psr-1/), [PSR-2](http://www.php-fig.org/psr/psr-2/), [PSR-4](http://www.php-fig.org/psr/psr-4/).\n\nIf you notice compliance oversights, please send a patch via [Pull Request](https://github.com/nilportugues/php-eloquent-repository/pulls).\n\n\n## Contribute\n\nContributions to the package are always welcome!\n\n* Report any bugs or issues you find on the [issue tracker](https://github.com/nilportugues/php-eloquent-repository/issues/new).\n* You can grab the source code at the package's [Git Repository](https://github.com/nilportugues/php-eloquent-repository).\n\n\n## Support\n\nGet in touch with me using one of the following means:\n\n - Emailing me at \u003ccontact@nilportugues.com\u003e\n - Opening an [Issue](https://github.com/nilportugues/php-eloquent-repository/issues/new)\n\n\n## Authors\n\n* [Nil Portugués Calderó](http://nilportugues.com)\n* [The Community Contributors](https://github.com/nilportugues/php-eloquent-repository/graphs/contributors)\n\n\n## License\nThe code base is licensed under the [MIT license](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Feloquent-repository","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnilportugues%2Feloquent-repository","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Feloquent-repository/lists"}