1. Go to this page and download the library: Download jtl/php-generic-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/ */
jtl / php-generic-collection example snippets
use JTL\Generic\GenericCollection;
class MyItemCollection extends GenericCollection {
public function __construct()
{
parent::__construct(MyItem::class);
}
}
$collection = new MyItemCollection();
$item1 = new MyItem(1);
$item2 = new MyItem(2);
$item3 = new MyItem(3);
$itemList = [
$item1,
$item2,
$item3
];
$collection[] = $item1;
$collection->addItemList([$item2, $item3]);
$collection2 = MyItemCollection::from($item1, $item2, $item3);
$collection3 = MyItemCollection::from(...$itemList);
$collection = new ObjectCollection(MyItem::class);
$item1 = new MyItem(1);
$item2 = new MyItem(2);
$item3 = new MyItem(3);
$itemList = [
$item1,
$item2,
$item3
];
$collection[] = $item1;
$collection->addItemList([$item2, $item3]);
$collection2 = ObjectCollection::from($item1, $item2, $item3);
$collection3 = ObjectCollection::from(...$itemList);
$collection = new ObjectCollection(MyItem::class);
$item1 = new MyItem(1);
$item2 = 'not MyItem';
$item3 = new MyItem(3);
$collection[] = $item1;
$collection[] = $item2; // <- Doesn't work. This will throw an exception + PHPStan will report the error
$collection->addItemList([$item2, $item3]); // <- This won't work either because $item2 is not a 'MyItem'
use JTL\Generic\GenericCollection;
class EvenCollection extends GenericCollection {
public function checkType($item): bool {
return $item % 2 === 0;
}
}
$e = new EvenCollection();
$e[] = 2;
$e[] = 4;
$e[] = 5; // <- Doesn't work. This will throw an exception
$itemList1 = new ItemCollection();
$itemList2 = new ItemCollection();
$item11 = new Item('123');
$item12 = new Item('789');
$item21 = new Item('456');
$item22 = new Item('0');
$itemList1[] = $item11;
$itemList1[] = $item12;
$itemList2[] = $item21;
$itemList2[] = $item21;
$zip = $itemList1->zip($itemList2);
foreach ($zip as $tuple) {
echo $tuple->getLeft()->getContent() . $tuple->getRight()->getContent() . "\n";
}
// Output:
123456
7890