本文介绍了PHP Generator中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果发生错误,通知谁使用我的生成器函数的最佳方法是什么,而不是像这段代码那样编写怪异的返回值或引发异常

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 */
}

推荐答案

<?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. :-)

这篇关于PHP Generator中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 04:47