Skip to content

Instantly share code, notes, and snippets.

@sileence
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)
<?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");
}
}
<?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