迭代器CsvFileIterator
测试 phpunit 的 dataProvider 依赖时需要读取 data.csv,继承了 Iterator 迭代器接口的 CsvFileIterator 可以通过 foreach 循环直接进行迭代读取。
<?php
namespace lib;
use Iterator;
class CsvFileIterator implements Iterator
{
private $handler;
private int $index = 0;
public function __construct($filepath)
{
$this->handler = fopen($filepath, 'r');
}
public function __destruct()
{
fclose($this->handler);
}
public function current(): mixed
{
return fgetcsv($this->handler, 2048);
}
public function rewind(): void
{
fseek($this->handler, 0);
$this->index = 0;
}
public function key(): int
{
return $this->index;
}
public function next(): void
{
$this->index++;
}
public function valid(): bool
{
return !feof($this->handler);
}
}
使用foreach进行迭代
$csv_items = new CsvFileIterator("../public/data.csv");
foreach ($csv_items as $key => $csv_item) {
var_dump($key, $csv_item);
}