Last Updated: September 29, 2021
·
24K
· italolelis

PHP Collections

What is it?

The Collections library is one of the most useful things in most modern languages​​, but for some reason PHP does not have this functionality as standard. Yes, we have the powerful PHP arrays, but they have a very dispersed and laborious API for us to use.

Therefore, the we created PHP Collections, an amazing library that combines the best practices adopted in collections. NET and Java working together with the power of PHP arrays.

Let's play a little with this library and see what it can do.

Installation

The PHP Collections is available for installation through the composer. So to get started, create a file in your project called composer.json and add the following lines:

{
    "autoload": {
        "psr-0": {
            "": ""
        }
    },
    "minimum-stability": "dev",
    "require": {
        "easyframework/collections": "2.1.*"
    }
}

Done that, we can run our installation, if you have already installed composer, go to your terminal (command line), navigate to your project's folder and run the following command:

$ composer install

Usage

The Collection class

The Collection class is equivalent to List class in .NET or ArrayList in Java. It is based on simple in PHP's non-associative arrays. Let's learn how to use it and add some elements to it:

$collection = new \Easy\Collections\Collection();
$collection->add('John');
$collection->add('Maria');
$collection->add('Anderson');

foreach($collection as $item){
    echo $item;
}

Simple, right? Let's continue with our example and count how many elements we have in this collection.

echo $colletion->count();

Great, now we know how to add and count collection's elements, but this is very simple, any array makes this task.

So let's make things better: how about we ordain the collection elements through some rule? For example, first I want to sort them in the natural numbers order and then alphabetically. Consider:

$collection->sort(); //by default the collection order is by keys
//This will order alphabetically
$colletion->sort(new \Easy\Collections\Comparer\StringComparer());

//here you can create your custom comparer
$collection->sort(new YourCustomComaparer());

Yeah, now we have something useful. We can for example create an comparer to a collection of dates in which we insert dates and order by the most recent. Well, we can do much more. Now lets get some element from the collection:

print_r($collection>contains("John")); //returns true

Ok, now we know a lot of things about the Collection class, I think we're ready to move on to the next type of collection called Dictionary.

Working with objects

We will work with some objects. Following our previous example, we will create a Person class. To do this, create a file in your project Person.php and do not worry about the 'require', as the composer automatically loads it for us:

class Person
{

    private $name;
    private $age;

    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getAge()
    {
        return $this->age;
    }

    public function setAge($age)
    {
        $this->age = $age;
    }

}

Now that we have our class, we instantiate a new collection and add it 6 people:

$collection = new \Easy\Collections\Collection();

$collection->add(new Person('John', 20));
$collection->add(new Person('Peter', 20));
$collection->add(new Person('Sophie', 21));
$collection->add(new Person('Angela', 29));
$collection->add(new Person('Maria', 19));
$collection->add(new Person('Anderson', 25));

foreach($collection as $item){
    echo $item->getName();
}

Pretty simple. The reason I wanted to show this is because the Expression Search API, it's very similar to LINQ API from .NET, which allows you to search with SQL semantics in collections.
Here's an example, I'd like to show only people who has 20 years old:

$criteria = new \Easy\Collections\Criteria();
$expr = $criteria->expr()->eq("age", 20);
$criteria->where($expr);
$collection = $collection->matching($criteria);

//will list John e Peter
foreach($collection as $item){
    echo $item->getName() . "-" . $item->getAge();
}

Now, we will list everyone whose name begins with the letter "A":

$criteria = new \Easy\Collections\Criteria();
$expr = $criteria->expr()->contains("name", "A");
$criteria->where($expr);
$collection = $collection->matching($criteria);

//will list Angela e Anderson
foreach($collection as $item){
    echo $item->getName() . "-" . $item->getAge();
}

See how simple it is performing more complex queries on collections with this API. In normal form, we would have to go through the complete collection, do some 'ifs' and 'strstr ()' to find the result. We have many other things we can use from this component, so be sure to explore it.

Other classes

We still have several other classes to work in the library, I will not show them all here, but here are some of the key:

  • Collection - A collection generic elements
  • Dictionary - A generic collection for elements with key and value
  • Queue - Represents a row and follows the standard FIFO (First in First out)
  • Stack - Represents a stack and follows the standard LIFO (Last in First out)
  • CollectionBase - Base for all collections, you can inherit it to create your own collections

Conclusion

I hope you enjoyed our tour of the Collections API. You may be wondering why use this library, and the answer is very simple .... Simplicity, organization and standardization. My intention is only to show you a useful tool to gain productivity.

I am responsible for the development of the library and still have much to improve on it, that's why I ask your help to build it, with documentation and coding is the same!

Link to Github repository: https://github.com/LellysInformatica/collections

Do not forget to take a look at the API documentation.