Intro into Symfony Doctrine PHP ArrayCollection

Summary:

The Doctrine ArrayCollection method offers OOP functionality to the normal PHP array. You can transform any PHP array into a collection. Check out the article for examples.

PHP ArrayCollection

PHP ArrayCollection is an instance of the Doctrine Collection interface. It is an OOP variant of the native PHP array. This article explains Doctrine and Collection interface. There are many examples of different Collection methods as well.

Introduction

An array is a fundamental data structure known for keeping data in contiguous memory space. Almost every programming language has an array built-in at its core. PHP arrays are unique in the sense that essentially, they are maps, having key and value pairs. However, they can be used as arrays too.

There are tons of articles about PHP arrays and the relevant functions at FuelingPHP. Arrays are highly usable and helpful for persisting multiple entities, but there are some scenarios where native PHP arrays can be hectic to deal with. A typical scenario is data persistence and mapping to and from a database.

Array PHP and OOP

Databases come in many shapes and flavors. But looking at the bigger picture, there are SQL and No-SQL databases. SQL databases are more structured and tabular, while No-SQL doesn’t care much about structure but focuses on storage and performance. Nonetheless, these databases interact in an Object-Oriented fashion, meaning that they expect objects for persistence and mapping.

Now, PHP arrays don’t exhibit the OOP patterns. All the functions relevant to native PHP arrays are not an object’s methods. Objects are more powerful and extendable, and there could be tons of easily callable methods. Therefore, the OOP pattern opens up a way for easily interacting with an underlying database.

One way to use an array in an OOP fashion is decorating it in a wrapper, a class, or an interface that makes it an object with all the OOP superpowers. Luckily, a library is out there that does the same thing.

Doctrine ArrayCollection

Doctrine is an open-source project that includes PHP libraries focused on dealing with databases – persistence and mapping. It has many cool projects, including Collection, that we’ll be exploring here. Collection is an interface, essentially a wrapper for native PHP arrays. PHP ArrayCollection is an instance of Collection.

Think of PHP ArrayCollection as a more extended form of PHP arrays. Many methods are readily available on Doctrine ArrayCollection, making it OOP-based, thus flexible and easy to use. PHP ArrayCollection includes many methods to add, modify and manipulate entities. Let’s begin exploring it through examples but let’s see how to install Doctrine Collection in the first place. 

Installing Doctrine ArrayCollection

Doctrine is an open-source project available on Github. It is not a built-in PHP library, and that’s why it has to be installed explicitly. For that, PHP requires composer, a package manager that does all the hard work for you. You can download it from composer official website. Follow the instructions and set up composer.

Once you’ve composer setup, proceed to the terminal and run the following command.

composer require doctrine/collections

This command downloads and installs doctrine collection and thus makes it available for use.

Instantiating ArrayCollection

So here’s an example of how to instantiate a PHP ArrayCollection object.

<?php
require __DIR__ . '/vendor/autoload.php';
 
use Doctrine\Common\Collections\ArrayCollection;
 
$collection = new ArrayCollection(['Anna', 'Brad', 'Drake']);
 
print_r($collection)
?>

The first two lines are necessary to include Doctrine Collection. The new ArrayCollection instantiates the object, an ArrayCollection of strings here. The output is somewhat peculiar.

Doctrine\Common\Collections\ArrayCollection Object
(
    [elements:Doctrine\Common\Collections\ArrayCollection:private] => Array
        (
            [0] => Anna
            [1] => Brad
            [2] => Drake
        )
 
)

All these unreadable details are related to the object. Let’s cut this crap and focus on the elements here, as we’ll be using methods that will affect array elements. So, let’s jump to the methods straight.

#1 – Doctrine ArrayCollection add method

Here’s how to add an element to the end of an ArrayCollection.

$collection->add('Franklin'); //['Anna', 'Brad', 'Drake', 'Franklin']

See that the collection invokes the methods in an OOP way, this is different than adding elements to an array with array_push.

#2 – Doctrine ArrayCollection remove method

Here’s how to remove an element by index.

$collection->remove(0); //['Brad', 'Drake', 'Franklin']

It removes the element at index 0, the first element.

#3 – Doctrine ArrayCollection remove element method

$collection->removeElement('Drake'); //['Brad', 'Franklin']

It looks for the element and removes it if exists.

#4 – ArrayCollection exists method

$collection->exists(function($key, $value) {
    return $value === 'Brad';
}); // true

The exists method takes a function with two arguments, key and value. It returns true based on a boolean condition as shown in the example.

#5 – Doctrine ArrayCollection getValues method

$collection->getValues(); //['Brad', 'Franklin']

This is similar to the array_values function.

#6 – Doctrine ArrayCollection getKeys method

$collection->getKeys(); //[0, 1]

This is similar to the array_keys function.

#7 –  ArrayCollection contains method

$collection->contains('Susi'); // false

 It looks for a value in the array and returns true if exists or false otherwise. 

#8 –  ArrayCollection containsKey method

$contains = $collection->containsKey(0); // true

This looks for a key in the array and returns true if exists.

#9 –  Doctrine ArrayCollection clear method

$collection->clear();

It unsets the array.

#10 –  ArrayCollection isEmpty method

$collection->isEmpty(); //true

If the collection has no elements then this method returns true.

Phew! Lots of methods. These are not all infact. There are many other methods listed in the official documentation. So, if you’re curious you can read about these methods.

Conclusion

This article introduces Doctrine, an open-source project about database storage and object mapping. Doctrine has numerous projects, including Collection, an interface that wraps the PHP native array in a class, giving it OOP capabilities. PHP ArrayCollections are a lot easier to work with and include numerous useful methods. 

So hopefully, you’ve learned something new today about PHP. If you’re determined to learn more, check PHP articles and tutorials at FuelingPHP

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems