jeromegamez / typed-collection by jeromegamez

Type-safe collections based on Laravel Collections
142,724
37
3
Package Data
Maintainer Username: jeromegamez
Maintainer Contact: jerome@gamez.name (Jérôme Gamez)
Package Create Date: 2017-08-31
Package Last Update: 2024-03-21
Language: PHP
License: MIT
Last Refreshed: 2024-04-18 15:07:59
Package Statistics
Total Downloads: 142,724
Monthly Downloads: 2,762
Daily Downloads: 156
Total Stars: 37
Total Watchers: 3
Total Forks: 5
Total Open Issues: 0

Type-safe PHP collections based on Laravel Collections

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.