Error in PHP Generator

旧街凉风 提交于 2020-01-25 13:08:13

问题


What is the best way to inform who use my generator function if something errors occurs, instead of writing weird return or raising exception like this piece of code

function csv_file_generator($csvFilename, $delimiter = ";", $enclousure = '"') {
    if(($csvHandler = fopen($csvFilename, 'rb')) === false) {
        return;
    }

    while (($row = fgetcsv($csvHandler, 0, $delimiter, $enclousure)) !== false) {
        yield $row;
    }

    if (feof($csvHandler) === false) {
        return;
    }

    if (fclose($csvHandler) === false) {
        return;
    }

    return; /* Exit Generator */
}

回答1:


<?php
class CsvFileGenerator {
    protected $fp;
    protected $delimiter;
    protected $enclousure;
    public function __construct($filename, $delimiter = ";", $enclousure = '"'){
        $this->delimiter=$delimiter;
        $this->enclousure=$enclousure;
        if(!file_exists($filename)){
            throw new Exception("file [$filename] dont exists");
        }
        if(!is_readable($filename)){
            throw new Exception("file [$filename] is not readable");
        }
        $this->fp =  fopen($filename, 'rb');
        if($this->fp === false){
            throw new Exception("cant open [$filename]");
        }
    }
    public function getGenerator(){
        while (($row = fgetcsv($this->fp, 0, $this->delimiter, $this->enclousure)) !== false) {
            yield $row;
        }
    }
    public function __destruct() {
        if($this->fp){
            fclose($this->fp);
        }
    }
}

foreach( (new CsvFileGenerator('mycsvfile.csv'))->getGenerator() as $line){
    #do some
}

One way to rome. :-)




回答2:


How about callbacks?

function gen($i, $on_close = null, $on_error = null) {
    while ($i--) {
        yield $i;

        if ($i === 5 && is_callable($on_close)) {
            $on_close();
        }
    }
}

$closed = false;
$gen = gen(10, function () use (&$closed) {
    $closed = true;
});

foreach ($gen as $x) {
    if ($closed) {
        break;
    }

    echo $x, PHP_EOL;
}

I'll admit its not pretty. Another options could be to return instances of special classes to let your main code know something is wrong.



来源:https://stackoverflow.com/questions/39898739/error-in-php-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!