/QueryBuilder.php Secret
Last active
August 20, 2019 09:17
Proof of concept to add query builder helpers directly in the repository (I'd still prefer to keep them in the query builder anyway)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Repository; | |
use BadMethodCallException; | |
use Doctrine\ORM\EntityRepository; | |
use Doctrine\ORM\QueryBuilder as DoctrineQueryBuilder; | |
class QueryBuilder extends DoctrineQueryBuilder | |
{ | |
private $repository; | |
public function setRepository(EntityRepository $repository) | |
{ | |
$this->repository = $repository; | |
return $this; | |
} | |
public function __call($name, $arguments) | |
{ | |
if ($this->repository) { | |
return $this->repository->$name($this, ...$arguments); | |
} | |
throw new BadMethodCallException("The method {$name} was not found"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Repository | |
{ | |
public function findStatsByCountry() | |
{ | |
//.... | |
$result = $this->createQueryBuilder('s') | |
//..... | |
->addSubSelectFromRepository($numberOfPayments, 'num_payments') | |
->addSubSelectFromRepository($totalAmount, 'amount') | |
//.... | |
->getQuery() | |
->getResult(); | |
//.... | |
} | |
public function addSubSelectFromRepository( | |
\Doctrine\ORM\QueryBuilder $queryBuilder, | |
\Doctrine\ORM\QueryBuilder $subselectQueryBuilder, | |
string $alias | |
) { | |
$queryBuilder->addSelect(sprintf( | |
'(%s) as %s', | |
$subselectQueryBuilder->getDQL(), $alias | |
)); | |
return $queryBuilder; | |
} | |
/** | |
* @return QueryBuilder | |
*/ | |
public function createQueryBuilder($alias, $indexBy = null) | |
{ | |
return (new QueryBuilder($this->_em)) | |
->select($alias) | |
->from($this->_entityName, $alias, $indexBy) | |
->setRepository($this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment