fernandozueet/laravel-doctrine-repository
Composer 安装命令:
composer require fernandozueet/laravel-doctrine-repository
包简介
Complete repository model with laravel doctrine
README 文档
README
Complete repository model with laravel doctrine.
Notices
The doctrine laravel library is used as the base of the repository class. Documentation of lib laravel doctrine
Requirements
- PHP 7.2
- Laravel 5.6 - Documentation
Packages
- doctrine: 2.6 - Documentation
- laravel-doctrine/orm: 1.4 - Documentation
- beberlei/doctrineextensions: 1.1 - Documentation
- symfony/property-access: 4.1 - Documentation
- symfony/serializer: 4.1 - Documentation
- syslogic/doctrine-json-functions: 2.0 - Documentation
Documentation
- Installation
- Step by step
- Examples
- Using different database connections
- Instantiating the created repository
- Entering Data (INSERT)
- Update Data (UPDATE)
- Update Query Data (UPDATE)
- Delete Data (DELETE)
- Select Data (SELECT)
- Find by id
- Transctions
- Dql
- Where and having options
- Order by options
- Group by options
- Extra functions
Installation
Install this package with composer:
composer require fernandozueet/laravel-doctrine-repository
After updating composer, add the ServiceProvider to the providers array in config/app.php
Ldr\Core\DoctrineRepositoryServiceProvider::class,
To publish the config use:
php artisan vendor:publish --tag="configRepository"
Step by step
1- Configure your connection to the database .env
2- Configure extra doctrine information. config/doctrine.php
3- Generate the entities
php artisan make:doctrine-repository:entities
4- Generate repository file.
File will be created by default app/Repositories folder. You can change the folder in the config/doctrine.php file.
ATTENTION!! use the same entity name
php artisan make:doctrine-repository User
Create file inside a folder
php artisan make:doctrine-repository SubPath/User
Examples
Example class repository
file: app/Repositories/User/UserDocRepository.php
<?php /** * User entity repository. * * Code generated by cli command. * * @see http://github.com/fernandozueet/laravel-doctrine-repository * * @copyright 2018 */ namespace App\Repositories\User; use Ldr\Src\DoctrineBaseRepository; class UserDocRepository extends DoctrineBaseRepository implements UserRepositoryInterface { /** * Construct. */ public function __construct() { parent::__construct(); $this->main($this->fkEntities, $this->mAlias, __CLASS__); } /*------------------------------------------------------------------------------------- * CONFIGS *-------------------------------------------------------------------------------------*/ /** * Foreign key entities names. * * @var array */ private $fkEntities = ['UserGenre']; /** * Main alias. * * @var string */ private $mAlias = 'u'; /*------------------------------------------------------------------------------------- * GENERAL *-------------------------------------------------------------------------------------*/ /** * Method of insertion in the database. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return object */ public function create(array $params): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setCreateArray([ 'fieldTest1', 'fieldTest2:fk=classNameFk', //foreign key ], $params); } /** * Method to update. To update more than one data, use the method updateQuery. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * @param int $id table id * * @return object */ public function update(array $params, int $id): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setUpdateArray([ 'fieldTest1', 'fieldTest2:fk=classNameFk', //foreign key ], $params, $id); } /** * Method to update. * Returns total of records affected. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return int */ public function updateQuery(array $params): int { return $this->mainUpdateQuery(function () use ($params) { $this->setUpdateArrayQuery([ 'fieldTest1', 'fieldTest2', ], $params); }); } /*------------------------------------------------------------------------------------- * SELECTS *-------------------------------------------------------------------------------------*/ /** * Settings select. * All the data from the table. */ public function selectAll() { //select $this->select("ug, {$this->mAlias}"); $this->from(); //joins $this->innerJoinUserGenre(); //set results (optional) - more information see the documentation. //$this->setQueryResultFormat('getResult'); //set hidration (optional) - more information see the documentation. //$this->addHydrateObject(); //$this->addCustomHydrationMode('ObjectAndScalarHydrator'); //$this->setReturn('doctrine'); //optional - default: array } /*------------------------------------------------------------------------------------- * JOINS *-------------------------------------------------------------------------------------*/ /** * Inner join UserGenre. */ private function innerJoinUserGenre() { $this->innerJoin("{$this->mAlias}.userGenre", 'ug'); } /*------------------------------------------------------------------------------------- * WHERES *-------------------------------------------------------------------------------------*/ /** * Where field u.id = ? * * @param int $value */ public function whereIdEq(int $value) { return $this->expr('id', '=', $value); } /*------------------------------------------------------------------------------------- * ORDERS BYS *-------------------------------------------------------------------------------------*/ /** * Sort by field u.id * * @param string $value DESC | ASC */ public function orderId(string $value = 'DESC') { $this->addOrderBy('id', $value); } /*------------------------------------------------------------------------------------- * GROUPS BYS *-------------------------------------------------------------------------------------*/ /** * Group by field u.id */ public function groupById() { $this->addGroupBy('id'); } /*------------------------------------------------------------------------------------- * HAVINGS *-------------------------------------------------------------------------------------*/ /** * Having field u.id = ? * * @param int $value */ public function havingIdEq(int $value) { return $this->expr('id', '=', $value); } /*------------------------------------------------------------------------------------- * DQL *-------------------------------------------------------------------------------------*/ //Dql methods here // }
Example interface repository
file: app/Repositories/User/UserRepositoryInterface.php
<?php /** * User repository interface. * * Code generated by cli command. * * @see http://github.com/fernandozueet/laravel-doctrine-repository * * @copyright 2018 */ namespace App\Repositories\User; interface UserRepositoryInterface { /*------------------------------------------------------------------------------------- * OTHERS *-------------------------------------------------------------------------------------*/ //Others here // public function whereIdEq(int $value); public function orderId(string $value = 'DESC'); public function groupById(); public function havingIdEq(int $value); /*------------------------------------------------------------------------------------- * GENERAL *-------------------------------------------------------------------------------------*/ public function create(array $params): object; public function update(array $params, int $id): object; public function updateQuery(array $params): int; public function selectAll(); public function setTransaction($conn); public function beginTransaction(); public function commitTransaction(); public function rollBackTransaction(); public function find(int $id, string $typeTreat = '', array $treatObject = []): object; public function createQuery(); public function setQuery($query); public function getQuery(); public function readQuery(string $typeTreat = '', array $treatObject = []): object; public function paginator(int $firstResult, int $limit); public function setMaxResults(int $limit); public function orderByRand(); public function setWhere($param); public function setAndWhere($param); public function setOrWhere($param); public function setCondOrWhere(); public function setCondAndWhere(); public function setCondNotWhere(); public function setParentStartWhere(); public function setParentEndWhere(); public function whereExpr($function); public function setHaving($param); public function setAndHaving($param); public function setOrHaving($param); public function setCondOrHaving(); public function setCondAndHaving(); public function setCondNotHaving(); public function setParentStartHaving(); public function setParentEndHaving(); public function havingExpr($function); public function deleteQuery(): bool; }
Example class service provider
file: app/Providers/UserDocRepositoryServiceProvider.php
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class UserDocRepositoryServiceProvider extends ServiceProvider { /** * Bootstrap services. * * @return void */ public function boot() { // } /** * Register services. * * @return void */ public function register() { $this->app->bind('\App\Repositories\User\UserRepositoryInterface', function ($app) { return new \App\Repositories\User\UserDocRepository(); }); } }
Using different database connections
Configure the new configuration in managers array the config/doctrine.php file you may notice that the default connection name is default. Insert a new position in the array with the settings
'managers' => [ 'default' => [ //..... ], 'otherConnection' => [ //----------------------------------------------- //Laravel doctrine repository config //----------------------------------------------- 'LdrConfig' => [ 'namespaceEntities' => 'App\Entities', ], //----------------------------------------------- 'dev' => env('APP_DEBUG', false), 'meta' => env('DOCTRINE_METADATA', 'annotations'), 'connection' => env('DB_CONNECTION', 'mysql'), 'namespaces' => [], 'paths' => [ base_path('app\Entities'), ], 'repository' => Doctrine\ORM\EntityRepository::class, 'proxies' => [ 'namespace' => false, 'path' => storage_path('proxies'), 'auto_generate' => env('DOCTRINE_PROXY_AUTOGENERATE', true), ], /* |-------------------------------------------------------------------------- | Doctrine events |-------------------------------------------------------------------------- | | The listener array expects the key to be a Doctrine event | e.g. Doctrine\ORM\Events::onFlush | */ 'events' => [ 'listeners' => [], 'subscribers' => [], ], 'filters' => [], /* |-------------------------------------------------------------------------- | Doctrine mapping types |-------------------------------------------------------------------------- | | Link a Database Type to a Local Doctrine Type | | Using 'enum' => 'string' is the same of: | $doctrineManager->extendAll(function (\Doctrine\ORM\Configuration $configuration, | \Doctrine\DBAL\Connection $connection, | \Doctrine\Common\EventManager $eventManager) { | $connection->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); | }); | | References: | http://doctrine-orm.readthedocs.org/en/latest/cookbook/custom-mapping-types.html | http://doctrine-dbal.readthedocs.org/en/latest/reference/types.html#custom-mapping-types | http://doctrine-orm.readthedocs.org/en/latest/cookbook/advanced-field-value-conversion-using-custom-mapping-types.html | http://doctrine-orm.readthedocs.org/en/latest/reference/basic-mapping.html#reference-mapping-types | http://symfony.com/doc/current/cookbook/doctrine/dbal.html#registering-custom-mapping-types-in-the-schematool |-------------------------------------------------------------------------- */ 'mapping_types' => [ //'enum' => 'string' ], ], ]
Using the new connection in the repository:
file: app/Repositories/User/UserDocRepository.php
public function __construct() { parent::__construct('otherConnection'); //set new connection here $this->main($this->fkEntities, $this->mAlias, __CLASS__); }
Instantiating the created repository
You can use the repository in your controller, service layer or wherever you want.
If you have created the repository with interface.
1 - Instantiating directly:
$userRepository = app('\App\Repositories\User\UserRepositoryInterface');
2 - Use controller:
/** * User repository * * @var \App\Repositories\User\UserRepositoryInterface */ private $userRepository; /** * Construct. * * @return void */ public function __construct(\App\Repositories\User\UserRepositoryInterface $userRepository) { $this->userRepository = $userRepository; }
if you have not created an interface.
1 - Instantiating directly:
$userRepository = app('\App\Repositories\User\UserDocRepository'); //or $userRepository = new \App\Repositories\User\UserDocRepository();
2 - Use controller:
/** * User repository * * @var \App\Repositories\User\UserDocRepository */ private $userRepository; /** * Construct. * * @return void */ public function __construct() { $this->userRepository = app('\App\Repositories\User\UserDocRepository'); //or $this->userRepository = new \App\Repositories\User\UserDocRepository(); }
Entering Data (INSERT)
example table: id, first_name, lastName, user_genre_id, updated_at, created_at.
created_at automatically inserted.
file: app/Repositories/User/UserDocRepository.php
/** * Method of insertion in the database. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return object */ public function create(array $params): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setCreateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params); }
Do not automatically inserted createdAt
/** * Method of insertion in the database. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return object */ public function create(array $params): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setCreateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, false); }
Dealing with the object of return:
/** * Method of insertion in the database. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return object */ public function create(array $params): object { //$this->setReturn('doctrine'); //optional - default: array //Ex 1: The return object will return only the firstName and lastName fields return $this->setCreateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, true, 'included', ['firstName','lastName']); //Ex 2: The return object will not return the firstName and lastName fields return $this->setCreateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, true, 'excluded', ['firstName','lastName']); }
Execute function:
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //insert $res = $userRepository->create([ 'firstName' => 'Alex', 'lastName' => 'Silva', 'userGenre' => 1 ]); //Returns the object. var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
Update Data (UPDATE)
example table: id, first_name, lastName, user_genre_id, updated_at, created_at.
updated_at automatically update.
ATTENTION! To update more than one data, use the method updateQuery.
file: app/Repositories/User/UserDocRepository.php
/** * Method to update. To update more than one data, use the method updateQuery. * Returns the object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * @param int $id table id * * @return object */ public function update(array $params, int $id): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setUpdateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, $id); }
Do not automatically update updatedAt
/** * Method to update. To update more than one data, use the method updateQuery. * Returns the object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * @param int $id table id * * @return object */ public function update(array $params, int $id): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setUpdateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, $id, false); }
Dealing with the object of return:
/** * Method to update. To update more than one data, use the method updateQuery. * Returns the object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * @param int $id table id * * @return object */ public function update(array $params, int $id): object { //$this->setReturn('doctrine'); //optional - default: array //Ex 1: The return object will return only the firstName and lastName fields return $this->setUpdateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, $id, true, 'included', ['firstName','lastName']); //Ex 2: The return object will not return the firstName and lastName fields return $this->setUpdateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, $id, true, 'excluded', ['firstName','lastName']); }
Execute function:
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //update $res = $userRepository->update([ 'firstName' => 'Alex 2', 'lastName' => 'Silva 2', 'userGenre' => 2 ], 1); //Returns the object var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
Update Query Data (UPDATE)
example table: id, first_name, lastName, user_genre_id, updated_at, created_at.
updated_at automatically update.
file: app/Repositories/User/UserDocRepository.php
/** * Method to update. * Returns total of records affected. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return int */ public function updateQuery(array $params): int { return $this->mainUpdateQuery(function () use ($params) { //set individual $this->set('firstName', $params['firstName']); //set json mysql $this->setJsonReplace('name', 'firstName', $params['firstName']); $this->setJsonSet('name', 'firstName', $params['firstName']); $this->setJsonInsert('name', 'firstName', $params['firstName']); //set all array $this->setUpdateArrayQuery([ 'firstName', 'lastName', 'userGenre', ], $params); //Do not automatically update updatedAt $this->setUpdateArrayQuery([ 'firstName', 'lastName', 'userGenre', ], $params, false); }); }
Creating the condition for the update:
/*------------------------------------------------------------------------------------- * WHERES *-------------------------------------------------------------------------------------*/ /** * Where field u.id = ? * * @param int $value */ public function whereIdEq(int $value) { return $this->expr('id', '=', $value); }
Execute function:
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //start query $userRepository->createQuery(); //where $userRepository->whereExpr(function () use ($userRepository) { //where id = 17 $userRepository->setWhere($userRepository->whereIdEq(17)); //add more conditions here // }); //update $res = $userRepository->updateQuery([ 'firstName' => 'Alex 2', 'lastName' => 'Silva 2', 'userGenre' => 2 ], 1); //total of records affected var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
Delete Data (DELETE)
Creating the condition for the delete:
file: app/Repositories/User/UserDocRepository.php
/*------------------------------------------------------------------------------------- * WHERES *-------------------------------------------------------------------------------------*/ /** * Where field u.id = ? * * @param int $value */ public function whereIdEq(int $value) { return $this->expr('id', '=', $value); }
Execute function:
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //start query $userRepository->createQuery(); //where $userRepository->whereExpr(function () use ($userRepository) { //where id = 17 $userRepository->setWhere($userRepository->whereIdEq(17)); //add more conditions here // }); //delete $res = $userRepository->deleteQuery(); //returned boolean var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
Select Data (SELECT)
Select settings:
file: app/Repositories/User/UserDocRepository.php
/*------------------------------------------------------------------------------------- * CONFIGS *-------------------------------------------------------------------------------------*/ /** * Foreign key entities names. * * @var array */ private $fkEntities = ['UserGenre']; /** * Main alias. * * @var string */ private $mAlias = 'u'; /*------------------------------------------------------------------------------------- * SELECTS *-------------------------------------------------------------------------------------*/ /** * Settings select. * All the data from the table. */ public function selectAll() { //select $this->select("ug, {$this->mAlias}"); //brings all the data //$this->select("{$this->mAlias}.id, {$this->mAlias}.firsName, {$this->mAlias}.lastName, ug.id, ug.desc"); //brings specific data //$this->select("{$this->mAlias}, PARTIAL ug.{id, desc}"); //add result getArrayResult //$this->addSelect("ug"); //add select several lines $this->from(); //joins $this->innerJoinUserGenre(); //set results (optional) //$this->setQueryResultFormat('getResult'); //$this->setQueryResultFormat('getArrayResult'); //$this->setQueryResultFormat('getSingleResult'); //$this->setQueryResultFormat('getOneOrNullResult'); //$this->setQueryResultFormat('getScalarResult'); //$this->setQueryResultFormat('getSingleScalarResult'); //set hidration (optional) //$this->addHydrateObject(); //$this->addHydrateArray(); //$this->addHydrateScalar(); //$this->addHydrateSingleScalar(); //$this->addCustomHydrationMode('ObjectAndScalarHydrator'); //$this->addCustomHydrationMode('ArrayHydratorCustom'); //$this->setReturn('doctrine'); //optional - default: array } /*------------------------------------------------------------------------------------- * JOINS *-------------------------------------------------------------------------------------*/ /** * Inner join UserLocate. */ private function innerJoinUserGenre() { $this->innerJoin("{$this->mAlias}.userGenre", 'ug'); //or //$this->innerJoin('UserGenre', 'ug', 'WITH', "ug.id = {$this->mAlias}.userGenre"); } /** * Left join UserLocate. */ private function leftJoinUserGenre() { $this->leftJoin("{$this->mAlias}.userGenre", 'ug'); //or //$this->leftJoin('UserGenre', 'ug', 'WITH', "ug.id = {$this->mAlias}.userGenre"); } /** * Join UserLocate. */ private function joinUserGenre() { $this->join("{$this->mAlias}.userGenre", 'ug'); //or //$this->join('UserGenre', 'ug', 'WITH', "ug.id = {$this->mAlias}.userGenre"); }
Creating the condition for the select:
/*------------------------------------------------------------------------------------- * WHERES *-------------------------------------------------------------------------------------*/ /** * Where field u.id = ? * * @param int $value */ public function whereIdEq(int $value) { return $this->expr('id', '=', $value); }
Creating the order by for the select:
/*------------------------------------------------------------------------------------- * ORDERS BYS *-------------------------------------------------------------------------------------*/ /** * Sort by field u.id * * @param string $value DESC | ASC */ public function orderId(string $value = 'DESC') { $this->addOrderBy('id', $value); }
Creating the group by for the select:
/*------------------------------------------------------------------------------------- * GROUPS BYS *-------------------------------------------------------------------------------------*/ /** * Group by field u.id */ public function groupById() { $this->addGroupBy('id'); }
Creating the having for the select:
/*------------------------------------------------------------------------------------- * HAVINGS *-------------------------------------------------------------------------------------*/ /** * Having field u.id = ? * * @param int $value */ public function havingIdEq(int $value) { return $this->expr('id', '=', $value); }
Execute function:
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //start query $userRepository->createQuery(); //settings select $userRepository->selectAll(); //where (optional) $userRepository->whereExpr(function () use ($userRepository) { //where id = 17 $userRepository->setWhere($userRepository->whereIdEq(17)); //where functions //$userRepository->setAndWhere($userRepository->whereFirstNameEq('Alex')); // AND firstName = 'alex' //$userRepository->setOrWhere($userRepository->whereFirstNameEq('Alex')); // OR firstName = 'alex' //$userRepository->setCondAndWhere(); // AND //$userRepository->setCondOrWhere(); // OR //$userRepository->setCondNotWhere(); // NOT //$userRepository->setParentStartWhere(); // ( //$userRepository->setParentEndWhere(); // ) //add more conditions here // }); //having (optional) $userRepository->havingExpr(function () use ($userRepository) { //having id = 17 $userRepository->setHaving($userRepository->havingIdEq(17)); //where functions //$userRepository->setAndHaving($userRepository->havingFirstNameEq('Alex')); // AND firstName = 'alex' //$userRepository->setOrHaving($userRepository->havingFirstNameEq('Alex')); // OR firstName = 'alex' //$userRepository->setCondAndHaving(); // AND //$userRepository->setCondOrHaving(); // OR //$userRepository->setCondOrHaving(); // NOT //$userRepository->setParentStartHaving(); // ( //$userRepository->setParentEndHaving(); // ) //add more conditions here // }); //order by (optional) $userRepository->orderId('ASC'); //order by rand (optional) $userRepository->orderByRand(); //group by (optional) $userRepository->groupById(); //max results (optional) $userRepository->setMaxResults(1); //paginator (optional) $userRepository->paginator(0, 1); //results - original result $res = $userRepository->readQuery(); //results - will return only the firstName and lastName fields. //Works only when all data is returned and no setQueryResultFormat is set. $res = $userRepository->readQuery('included', ['firstName','lastName']); //results - will not return the firstName and lastName fields. //Works only when all data is returned and no setQueryResultFormat is set. $res = $userRepository->readQuery('excluded', ['firstName','lastName']); //returned results var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
Find by id
Execute function:
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //find $res = $userRepository->find(36); //or //find - will return only the firstName and lastName fields. $res = $userRepository->find(36, 'included', ['firstName','lastName']); //or //find - will not return the firstName and lastName fields. $res = $userRepository->find(36, 'excluded', ['firstName','lastName']); //returned results var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
Transctions
Execute function:
$userGenre = app('\App\Repositories\UserGenre\UserGenreRepositoryInterface'); $userRepository = app('\App\Repositories\User\UserRepositoryInterface'); //init transaction $transaction = $userGenre->beginTransaction(); //----------------------- //insert userGenre try { //set transaction $userGenre->setTransaction($transaction); //insert $res = $userGenre->create([ 'desc' => 'woman' ]); } catch (\Exception $e) { //rollBack $userGenre->rollBackTransaction(); //error return $e->getMessage(); } //----------------------- //insert user try { //setTransaction $userRepository->setTransaction($transaction); //insert $res = $userRepository->create([ 'firstName' => 'Alex', 'lastName' => 'Silva', 'userGenre' => $res->id ]); } catch (\Exception $e) { //rollBack $userRepository->rollBackTransaction($transaction); //error return $e->getMessage(); } //commit data $userGenre->commitTransaction();
Dql
Creating query:
file: app/Repositories/User/UserDocRepository.php
/*------------------------------------------------------------------------------------- * DQL *-------------------------------------------------------------------------------------*/ /** * Select with dql. * * @param array $params * @return object */ public function selectDql(array $params): object { $this->createQueryDql("SELECT u FROM {$this->entityMain} AS u WHERE u.id = ?0"); //dql query $this->setParameterDql(0, $params['id']); //set parameter $this->paginatorDql($params['firstResult'], $params['maxResults']); //paginator //$this->setReturn('doctrine'); //optional - default: array //result return $this->getResultDql(); //or //result - will return only the firstName and lastName fields. return $this->getResultDql('included', ['firstName','lastName']); //or //find - will not return the firstName and lastName fields. return $this->getResultDql('excluded', ['firstName','lastName']); }
Execute function:
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //dql select $res = $userRepository->selectDql([ 'id' => 1, 'firstResult' => 0, 'maxResults' => 5 ]); //returned results var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
Where and having options
These options are valid for where and having.
file: app/Repositories/User/UserDocRepository.php
/** * Where field u.id = ? * * @param int $id */ public function whereIdEq(int $id) { return $this->expr('id', '=', $id); } /** * Where field json u.name.firstname LIKE ? * * @param string $value */ public function whereNameFirstNameLike(string $value) { return $this->expr($this->fieldJson('name', 'firstName'), 'LIKE', "%$value%", false); } /** * Where field ug.id = ? * * @param int $id */ public function whereUserGenreIdEq(int $id) { return $this->expr('ug.id', '=', $id, false); } /** * Where field u.id > ? * * @param int $id */ public function whereIdGt(int $id) { return $this->expr('id', '>', $id); } /** * Where field u.id >= ? * * @param int $id */ public function whereIdGte(int $id) { return $this->expr('id', '>=', $id); } /** * Where field u.id < ? * * @param int $id */ public function whereIdLt(int $id) { return $this->expr('id', '<', $id); } /** * Where field u.id <= ? * * @param int $id */ public function whereIdLte(int $id) { return $this->expr('id', '<=', $id); } /** * Where field u.id <> ? * * @param int $id */ public function whereIdNeq(int $id) { return $this->expr('id', '<>', $id); } /** * Where field u.id IS NULL */ public function whereIdIsNull() { return $this->expr('id', 'IS NULL', ''); } /** * Where field u.id IS NOT NULL */ public function whereIdIsNotNull() { return $this->expr('id', 'IS NOT NULL', ''); } /** * Where field u.id * ? * * @param int $id */ public function whereIdProd(int $id) { return $this->expr('id', '*', $id); } /** * Where field u.id - ? * * @param int $id */ public function whereIdDiff(int $id) { return $this->expr('id', '-', $id); } /** * Where field u.id + ? * * @param int $id */ public function whereIdSum(int $id) { return $this->expr('id', '+', $id); } /** * Where field u.id / ? * * @param int $id */ public function whereIdQuot(int $id) { return $this->expr('id', '/', $id); } /** * Where field u.id IN (?,?,?,...) * * @param array $values */ public function whereIdIn(array $values) { return $this->expr('id', 'IN', $values); } /** * Where field u.id NOT IN (?,?,?,...) * * @param array $values */ public function whereIdNotIn(array $values) { return $this->expr('id', 'NOT IN', $values); } /** * Where field u.firstName LIKE ? * * @param string $value */ public function whereFirstNameLike(string $value) { return $this->expr('firstName', 'LIKE', "%$value%"); } /** * Where field u.firstName NOT LIKE ? * * @param string $value */ public function whereFirstNameNotLike(string $value) { return $this->expr('firstName', 'NOT LIKE', "%$value%"); } /** * Where field u.createdAt BETWEEN ? AND ? * * @param string $value1 * @param string $value2 * @return void */ public function whereCreatedAtBetween(string $value1, string $value2) { return $this->expr('createdAt', '', $this->exprBetween($value1, $value2), true, false); } /** * Where field u.createdAt NOT BETWEEN ? AND ? * * @param string $value1 * @param string $value2 * @return void */ public function whereCreatedAtNotBetween(string $value1, string $value2) { return $this->expr('createdAt', 'NOT', $this->exprBetween($value1, $value2), true, false); }
Order by options
file: app/Repositories/User/UserDocRepository.php
/** * Sort by field u.id * * @param string $value DESC | ASC */ public function orderId(string $value = 'DESC') { $this->addOrderBy('id', $value); } /** * Sort by field ug.id * * @param string $value DESC | ASC */ public function orderUserGenreId(string $value = 'DESC') { $this->addOrderBy('ug.id', $value, false); }
Group by options
file: app/Repositories/User/UserDocRepository.php
/** * Group by field u.id */ public function groupById() { $this->addGroupBy('id'); } /** * Group by field ug.id */ public function groupByUserGenreId() { $this->addGroupBy('ug.id', false); }
Extra functions
file: app/Repositories/User/UserDocRepository.php
//principal entity namespace (string) var_dump($this->entityMain);
//namespaces of entities (array) var_dump($this->ent);
//principal entity name (string) var_dump($this->mainNameEntity);
//search entity (string) var_dump($this->searchEnt('UserGenre'));
//get reference $this->getReference("UserGenre", $id);
//persist $this->persist($entity);
//flush $this->flush();
//clear $this->clear();
//json extract mysql - name.firstName $this->fieldJson('name', 'firstName');
//created name parameter. //will pass the die to bind :dc_value1 $this->createNamedParameter($params['firstName']);
Contributing
Please see CONTRIBUTING for details.
Security
If you discover security related issues, please email fernandozueet@hotmail.com instead of using the issue tracker.
Credits
License
The PHP Upload and Image Manipulation is licensed under the MIT license. See License File for more information.
fernandozueet/laravel-doctrine-repository 适用场景与选型建议
fernandozueet/laravel-doctrine-repository 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 116 次下载、GitHub Stars 达 1, 最近一次更新时间为 2018 年 09 月 04 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「repository」 「doctrine」 「crud」 「laravel」 「laravel doctrine」 「doctrine repository」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 fernandozueet/laravel-doctrine-repository 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 fernandozueet/laravel-doctrine-repository 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 fernandozueet/laravel-doctrine-repository 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
repository php library
Gii Generator for double model generation
A PSR-7 compatible library for making CRUD API endpoints
Laravel 5 - Repositories to the database layer
Admin panel generator for Laravel 8 and based on Vuetify Admin, a separate SPA admin framework running on top of REST APIs.
Make pimcore migration simple
统计信息
- 总下载量: 116
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 6
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-09-04