gamez/typed-collection

Type-safe collections based on Laravel Collections

2.0 2017-10-17 17:50 UTC

README

Latest Stable Version Total Downloads Build Status

Installation

The package can be installed with Composer:

$ composer require gamez/typed-collection

Usage

use Gamez\Illuminate\Support\TypedCollection;

class Person
{
    public $name;

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

class People extends TypedCollection
{
    protected static $allowedTypes = [Person::class];
}

People::make([new Person('Taylor'), new Person('Jeffrey')])
    ->each(function (Person $person) {
        printf("This is %s.\n", $person->name);
    });
/* Output:
This is Taylor.
This is Jeffrey.
*/

try {
    People::make('Nope!');
} catch (InvalidArgumentException $e) {
    echo $e->getMessage().PHP_EOL;
    // Output: A People collection only accepts objects of the following types: Person.
}

For further information on how to use Laravel Collections, have a look at the official documentation.