koriym / loop
Converts iterable data sets (e.g., database results, CSV files) into an entity list generator with loop context (isFirst, isLast, index, iteration).
Installs: 5 183
Dependents: 0
Suggesters: 0
Security: 0
Stars: 7
Watchers: 2
Forks: 1
Open Issues: 0
Requires
- php: ^7.2 || ^8.0
Requires (Dev)
- bamarni/composer-bin-plugin: ^1.4
- phpunit/phpunit: ^8.5.24 || ^9.5
This package is auto-updated.
Last update: 2024-10-09 05:23:09 UTC
README
Koriym.Loop is a PHP library that converts various iterable data sets, such as database result sets, CSV files, or any other iterable structures, into an entity list generator. This makes it easy to use in views by providing looping information such as isFirst, isLast, index, and iteration, similar to the loop processing found in template engines like Twig.
Installation
composer require koriym/loop
Usage
Basic Example
The following example demonstrates how to use Koriym.Loop with a simple User class and a result set:
class User { public function __construct( public readonly int $id, public readonly string $name ){} } // Database result sets or csv content $resultSet = [ ['id' => 1, 'name' => 'ray'], ['id' => 2, 'name' => 'bear'], ['id' => 3, 'name' => 'alps'], ]; /** @var Generator<Loop, User, mixed, void> $users */ $users = (new LoopGen)($resultSet, User::class); foreach ($users as $user) { echo $user->name; }
Loop information
Loop information can be accessed from the array keys, providing details such as whether the current item is the first or last in the list:
/** @var Loop $loop */ foreach ($users as $loop => $user) { echo match(true) { $loop->isFirst && $loop->isLast => "<ul><li>{$user->name}</ul>", $loop->isFirst => "<ul><li>{$user->name}", $loop->isLast => "<li>{$user->name}</ul>", default => "<li>{$user->name}" }; }
Loop Properties
Injection
Dependent instances can be injected into the entity by specifying them as the third argument. Specify the key as the name of the parameter and the value as the instance.
$dependencies = [ $varName => $insntance, 'dateTime' => new DateTime(), // DateTime instance is injected ]; $users = (new LoopGen)($resultSet, User::class, $dependencies);
Iterator Support
Koriym.Loop supports iterators as well as arrays. Here's an example using a CSV iterator:
class Row { public function __construct( public readonly int $id, public readonly string $name ){} } // Retrieve contents of csv file as list<Row> $csvIterator = new ogrrd\CsvIterator\CsvIterator($csvFilePath); /** @var list<Row> $csvRowList */ $csvRowList = (new LoopGen)($csvIterator, Row::class); foreach ($csvRowList as $loop => $row) { if ($loop->isFirst) { continue; // Skip header } echo $row->name; }
This library provides a flexible and convenient way to handle looping through result sets and other iterable data structures in PHP, with additional context information about the loop's state.