The following example shows some extract of an code example. Invoking the QueryBuilder
of Doctrine DBAL is done twice there - once for executing a SELECT(*)
statement and prior to that executing a COUNT(*)
statement.
Common settings like table, conditions, sorting order and result limits are applied to the reused QueryBuilder
object.
Questions
- Are there drawbacks of implicitly reusing
$queryBuilder
like shown in the example? - Is it suggested to just copy-paste the code for separate
QueryBuilder
instances? - Are the side-effects in using
clone $queryBuilder
?
Code Example
/**
* @param array $arguments
* @return string
*/
private function getOutput(array $arguments)
{
/** @var \Doctrine\DBAL\Connection $connection */
$connection = $this->getConnection();
$queryBuilder = $connection
->createQueryBuilder()
->from('some_table')
->orderBy('sorting')
->setMaxResults(100);
$condition = $queryBuilder->expr()->andX();
// ... build conditions
$queryBuilder->where($condition);
$count = $queryBuilder->select('COUNT(*)')->execute()->fetchColumn(0);
if ($count === 0) {
return 'There is nothing to show';
}
if ($count > 100) {
$output = 'Showing first 100 results only:' . PHP_EOL;
} else {
$output = 'Showing all results:' . PHP_EOL;
}
// implicitly reusing previously defined settings
// (table, where, orderBy & maxResults)
$statement = $queryBuilder->select('*')->execute();
foreach ($statement as $item) {
$output .= $this->renderItem($item) . PHP_EOL;
}
return $output;
}