Frequently Used ArrayCollection Methods
Continuing on with our look into Doctrine's Collection interface, in this video we cover:
isEmpty()
remove()
removeElement()
contains()
containsKey()
getKeys()
getValues()
slice()
set()
toArray()
first()
last()
getIterator()
current()
next()
An important point to understand when working with an ArrayCollection
that has been created from a Doctrine query result is that changes made to the collection will not affect the data in your database - unless you explicitly say to do so.
An example of this would be:
// let's assume we are inside a Symfony controller action, and $em is our EntityManager
$topics = $em->getRepository('AppBundle:Topic')->findAll(); // returns an array
$collection = new ArrayCollection($topics);
$collection->remove(5);
In the example above we have removed an item from our ArrayCollection
, but not from our database.
This can be good or bad, depending on your perspective / expected outcome.
If you do wish to remove the item from your database also, you can do so quite easily - as remember, this ArrayCollection
was directly created from our Doctrine result set, so the items in this collection are known entities in our database.
$topics = $em->getRepository('AppBundle:Topic')->findAll(); // returns an array
$collection = new ArrayCollection($topics);
$topic = $collection->get(5);
$em->remove($topic);
$em->flush();
If you created the ArrayCollection
from a plain old PHP array though, that example wouldn't work because the data never existed in the database in the first place.
No ID? No Problem
What if we have the object we want to remove, but we don't know what ID that object has in the ArrayCollection
? Surely having to look up the ID first would be needless?
Yes, we can instead, use removeElement()
and pass in the object we wish to remove, and let the ArrayCollection
implementation handle that for us in the background. Free functionality! The best kind.
// let's assume we are inside a Symfony controller action, and $em is our EntityManager
$topics = $em->getRepository('AppBundle:Topic')->findAll(); // returns an array
$collection = new ArrayCollection($topics);
$topic = $collection->get(5);
$collection->removeElement(topic);
Again, and for all examples - this is not going to affect the underlying data in the database. This only removes the thing from the collection.
We cover a lot of the common Collection
interface methods in this video, and in the next videos we will move on to the more powerful, perhaps less frequently used methods.