I have the problem, that I have two controllers. One is a restful controller which only handles json
data and returns a JsonModel
, and the other one is a default controller which returns a ViewModel
Now I have the problem, that my method only returns an array
of entities, which is correct for the default controller, but my restful controller needs the entities as an array. How can I handle this?
MealController
class MealController extends AbstractRestfulController { protected $mealService; public function getList() { $meals = $this->mealService->getAllMeals(); return new JsonModel($meals); } }
MealService
class MealService { protected $mealRepository; public function getAllMeals() { return $this->mealRepository->findAll(); } }
MealRepository
class MealRepository extends EntityRepository { public function findAll() { $queryBuilder = $this->createQueryBuilder('meal') ->orderBy('title'); return $queryBuilder->getQuery()->getResult(); } }
Advertisement
Answer
You coud use for that Array Hydration. It allows to specify a hydration mode when executing queries, and change the data type of the results returned. You just need to use the constant Query::HYDRATE_ARRAY
as parameter in your getResult()
method :
public function findAll() { $queryBuilder = $this->createQueryBuilder('meal') ->orderBy('title'); return $queryBuilder->getQuery()->getResult(DoctrineORMQuery::HYDRATE_ARRAY); }
Maybe you could also take a look at the EntitySerializer class which let you create an array of json from an entity :
$entitySerializer = new EntitySerializer($em); $entityAsArray = $entitySerializer->toArray($entity);