The Basics of A Doctrine Collection


In this first video we take an overview of all the available methods on Doctrine's Collection interface.

Some of them are straightforward - add, isEmpty, toArray - and some are more confusing and scary sounding - map, partition, and forAll.

The good news is, none of these are particularly difficult to use or understand - as long as you have someone sat next to you to show you how to use them. That's where I come in :)

The data set I am using throughout this tutorial series is from the Doctrine Performance Optimisations video tutorial series, but these methods work with any Doctrine result set - or in fact, any array at all.

If you don't have any data to hand, I highly recommend using Will Durand's Faker Bundle which is a perfect way to generate as much made-up / faked data as you desire. It really is very useful, and a great way to seed a project with some dummy data whether for testing or just to give a client / your boss a view of what the end result could potentially look like.

Creating A Doctrine ArrayCollection

Creating a new ArrayCollection() is very straightforward.

Make sure you have the correct use statement at the top of your class definition:

<?php

namespace YourBundle\Whatever;

use Doctrine\Common\Collections\ArrayCollection;
// *snip snip*

And then simply new up a new instance of ArrayCollection as required, optionally passing in your existing array in the ArrayCollection constructor.

$myArrayCollection = new ArrayCollection();

// or

$myArray = [1,2,3,4,5]; // php 5.4+ array syntax
$myArrayCollection = new ArrayCollection($myArray); // passing in the existing array via constructor

Both of these will work. If your ArrayCollection is constructed without any data, or you need to add more data after you have instantiated your new ArrayCollection then that couldn't be easier. Simply call $myArrayCollection->add('whatever');.

ArrayCollection Methods Covered In This Video

  • add
  • clear
  • get
  • contains

Episodes

# Title Duration
1 The Basics of A Doctrine Collection 06:04
2 Frequently Used ArrayCollection Methods 06:58
3 Filter, Map, and Exists 06:11
4 forAll, partition, slice, and more 06:38