PHP:在类__constructor中使用file_get_contents()是否不好?

时间:2019-06-16 17:26:54

标签: php json class file-get-contents

我有一个用json字符串制作经济日历的类。唯一的问题是我不知道我应该在类file_get_contents()中使用__constructor()(从api获取数据)还是应该将json字符串传递给{{1} }来自我的__constructor区块?

哪种做法更好,为什么呢?

到目前为止,这是我的课程( EconomicCalendar.php ):

try{...}catch{...}

以下是输出日历的代码( ec.php ):

class EconomicCalendar{

    private $_data,
            $_calendar = [];

    public function __construct($url){
        $this->_data = json_decode(file_get_contents($url));
    }

    private function make_economic_calendar(){
        foreach($this->_data->events as $e){
            $arr[$e->date][] = [
                'title' => $e->title,
                'date' => $e->date
            ];
        } 

        if(is_array($arr) && count($arr) >= 1){
            return (object)$arr;
        } else{
            throw new Exception('EC was not created');
        }
    }

    public function get_calendar(){
        $this->_calendar = $this->make_economic_calendar();
        return $this->_calendar;
    }

}

谢谢!

1 个答案:

答案 0 :(得分:2)

使IO操作越晚(或越少)越好。因此,如果您要初始化数据,我建议您使用“命名构造函数”

class EconomicCalendar {

    ...

    public function __construct($data){
        $this->_data = $data;
    }

    ...

    public static function fromUrl($url){
        return new self(json_decode(file_get_contents($url)));
    }

}

和用法:

$instance = EconomicCalendar::fromUrl('https://api.example.com/ec?token={MY_TOKEN}');

将IO移动和解码到专用功能更接近于单一职责原则(静态时为IO,类实例为逻辑)。