PHP code example of cunningsoft / generic-list

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

    

cunningsoft / generic-list example snippets




declare(strict_types=1);

namespace MyApp;

use ArrayIterator;
use Cunningsoft\GenericList\ListConstructor;
use Cunningsoft\GenericList\ListType;

final class UserList implements ListType
{
    use UnsortedListConstructor;

    public function getIterator(): ArrayIterator
    {
        return $this->list->getIterator();
    }

    protected function getElementType(): string
    {
        return User::class;
    }
}

    public function isEmpty(): self
    {
        return $this->list->isEmpty();
    }

    public function filterOnlyActive(): self
    {
        return new self($this->list->filter(static function (User $user): bool {
            return $user->isActive();
        });
    }

$users = new UserList([$userA, $userB, $userC]);
if ($users->filterOnlyActive()->isEmpty()) {
    echo 'No active users!';
}



declare(strict_types=1);

namespace MyApp;

use ArrayIterator;
use Cunningsoft\GenericList\ListConstructor;
use Cunningsoft\GenericList\ListType;

final class SortedByAgeUserList implements ListType
{
    use SortedListConstructor;

    public function getIterator(): ArrayIterator
    {
        return $this->list->getIterator();
    }

    protected function getElementType(): string
    {
        return User::class;
    }

    protected function getSortFunction(): callable
    {
        return static function (User $userA, User $userB): int {
            return $userA->getAge() <=> $userB->getAge();
        };
    }
}