Skip to content

Type-safe collections based on Laravel Collections

Notifications You must be signed in to change notification settings

mad-briller/typed-collection

 
 

Repository files navigation

Type-safe PHP collections based on Laravel Collections

Latest Stable Version Total Downloads Build Status Sponsor

Installation

The package can be installed with Composer:

$ composer require gamez/typed-collection

Usage

class Person
{
    public $name;

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

$taylor = new Person('Taylor');
$jeffrey = new Person('Jeffrey');

Typed Collections

use Gamez\Illuminate\Support\TypedCollection;

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

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

try {
    People::make('Not a person');
} catch (InvalidArgumentException $e) {
    echo $e->getMessage().PHP_EOL;
}
/* Output:
Output: A People collection only accepts objects of the following type(s): Person.
*/

Lazy Typed Collections

use Gamez\Illuminate\Support\LazyTypedCollection;

class LazyPeople extends LazyTypedCollection
{
    protected static $allowedTypes = [Person::class];
}

$lazyPeople = LazyPeople::make([$taylor, $jeffrey])
    ->each(function (Person $person) {
        printf("This is %s.\n", $person->name);
    });
/* Output:
This is Lazy Taylor.
This is Lazy Jeffrey.
*/

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

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

About

Type-safe collections based on Laravel Collections

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%