PHP code example of gamez / typed-collection

1. Go to this page and download the library: Download gamez/typed-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/ */

    

gamez / typed-collection example snippets


class Person
{
    public $name;

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

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

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 items of the following type(s): Person.
*/

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.
*/

$dateTimes = typedCollect([new DateTime(), new DateTime()], DateTimeInterface::class);