对于一个项目,我需要以 JSON 格式提供大量不同的数据。所有信息都将在同一页面上使用,因此一次调用将产生最少的开销。这些信息都涉及同一个数据库对象,并且在页面上都是必需的。它基本上是一个或多个特定类型的对象数量的集合(这些类型都是布尔值),我们需要知道很多不同的变体。我使用了下面的代码,但我的同事认为我把它放在 JSON 列表中的方式有点笨拙,代码可以有更好的性能。我该如何改进这段代码?
public function getContactsStatisticsAction()
{
$response = new Response();
$json = array();
$em = $this->getDoctrine()->getEntityManager();
$cr = $em->getRepository('BlaCoreBundle:Company');
$json['numberOfCompanies'] = $cr->numberOfCompanies();
$json['numberOfAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true));
$json['numberOfCompetitors'] = $cr->numberOfCompanies(array("typeCompetitor" => true));
$json['numberOfSuppliers'] = $cr->numberOfCompanies(array("typeSupplier" => true));
$json['numberOfOthers'] = $cr->numberOfCompanies(array("typeOther" => true));
$json['numberOfUnassigned'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false,"typeSupplier" => false,"typeOther" => false));
$json['numberOfJustAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => false, "typeSupplier" => false));
$json['numberOfJustCompetitors'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false, "typeSupplier" => false));
$json['numberOfJustSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false, "typeSupplier" => false));
$json['numberOfCompetitorAndAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => true, "typeSupplier" => false));
$json['numberOfCompetitorAndSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => true, "typeSupplier" => true));
$json['numberOfSupplierAndAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => false, "typeSupplier" => true));
$json['numberOfCompaniesAndAccountsAndSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => true, "typeSupplier" => true));
$response->setContent(json_encode($json));
return $response;
}
public function numberOfCompanies($filters = array())
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('count(c.id)');
$qb->from('BlaCoreBundle:Company', 'c');
$sizeFilters = count ($filters);
$keys = array_keys($filters);
if($sizeFilters >= 1){
$qb->where('c.' . $keys[0] . ' = ' . (int) $filters[$keys[0]]);
}
for($i = 1; $i < $sizeFilters; $i++){
$qb->andWhere('c.' . $keys[$i] . ' = ' . (int) $filters[$keys[$i]]);
}
return $qb->getQuery()->getSingleScalarResult();
}