PHP code example of kuaukutsu / ds-collection

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

    

kuaukutsu / ds-collection example snippets


$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));

$collectionOther = new DtoCollection();
$collectionOther->attach(new Dto(3, 'third'));
$collectionOther->attach(new Dto(4, 'fourth'));

$collection->merge($collectionOther);

$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));
$collection->attach(new Dto(3, 'first'));
$collection->attach(new Dto(4, 'second'));

$collectionByFiltered = $collection->filter(
    static fn(Dto $dto): bool => $dto->name === 'first'
);

$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));
$collection->attach(new Dto(3, 'first'));
$collection->attach(new Dto(4, 'second'));

$sortCollection = $collection->sort(
    static fn(Dto $a, Dto $b): int => strcmp($a->name, $b->name)
);

/**
 * @param Dto $item
 * @return int
 */
protected function indexBy($item): int
{
    return $item->id;
}

/**
 * @param Dto $item
 * @return string
 */
protected function indexBy($item): string
{
    return $item->name;
}

$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));

$dto = $collection->get('second');

/**
 * @param Dto $item
 * @return array<scalar>
 */
protected function indexBy($item): array
{
    return [$item->id, $item->name];
}

$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));
$collection->attach(new Dto(3, 'third'));

$dto = $collection->get(2, 'second');