2

I have a problem with Doctrine2 find methods. They all return as array instead of ArrayCollection.

Is there any away to force them to return a ArrayCollection? I remember this also happened with a custom repository query. I had to do: new ArrayCollection($result).

brpaz
  • 3,618
  • 9
  • 48
  • 75
  • ArrayCollection is meant to support OneToMany or ManyToMany collections of relations, but find* methods just returns some results, no need for a Collection here. – AlterPHP Aug 12 '13 at 15:31
  • OK. But it would be nice to do $results->count() instead of count($results) or having any of the methods of ArrayCollection instead of a flat array – brpaz Aug 12 '13 at 15:35
  • 1
    PHP is not Java so arrays are still "poor native" types. ArrayCollection are object oriented arrays, but do not add some new features. It just provides an object interface to map collections in entities, not to break the object structure when handling relations. – AlterPHP Aug 13 '13 at 07:31

1 Answers1

1

Here is my dirty, low-tech approach.

// your findBy* here:
$entities = $em->getRepository($entclass)->findBy($entFilter, array('id' => 'DESC'));

// my one-liner conversion here:
$entitiesCollection= new \Doctrine\Common\Collections\ArrayCollection($entities);

Then I confirmed I could use those handy ArrayCollection methods like last(), count(), contains(), etc.

var_dump($entitiesCollection->count(), $entitiesCollection); print \strftime('%c') . __FILE__ . __LINE__ . __FUNCTION__; die;  
Marcos
  • 4,796
  • 5
  • 40
  • 64