PHP code example of pogulailo / collection

1. Go to this page and download the library: Download pogulailo/collection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pogulailo / collection example snippets


use Pogulailo\Collection\GenericCollection;

class CustomerCollection extends GenericCollection
{
    public function __construct(...$values)
    {
        parent::__construct(Customer::class, ...$values);
    }
}

function getCustomers(): CustomerCollection
{
    $customers = new CustomerCollection();
    
    $customers->append(new Customer());
    $customers->append(new Customer());
    $customers->append(new Customer());
    
    return $customers;
}

function doSomething(CustomerCollection $customers): void
{
    foreach ($customers as $customer) {
        // Do what you need to do
    }
}

$customers = getCustomers();
doSomething($customers);

use Pogulailo\Collection\GenericCollection;

function getCustomers(): GenericCollection
{
    $customers = new GenericCollection(Customer::class);
    
    $customers->append(new Customer());
    $customers->append(new Customer());
    $customers->append(new Customer());
    
    return $customers;
}

function doSomething(GenericCollection $customers): void
{
    // In this case, you need to check the collection type first
    if ($customers->getType() !== Customer::class) {
        throw new Exception('I need customers, more customers...')
    }
    
    foreach ($customers as $customer) {
        // Do what you need to do
    }
}

$customers = getCustomers();
doSomething($customers);