首页 > 解决方案 > PHP:在类 __constructor 中使用 file_get_contents() 是一种不好的做法吗?

问题描述

我有一门用 json 字符串制作经济日历的课程。唯一的问题是我不知道我是否应该file_get_contents()在我的类中使用(从 api 获取数据)__constructor()或者我应该只将 json 字符串传递给__constructor我的try{...}catch{...}块?

哪种做法更好,为什么?

到目前为止,这是我的课程(EconomicCalendar.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;
    }

}

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

spl_autoload_register(function($class){
    require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . $class . '.php';
});

try {
    $c = new EconomicCalendar('https://api.example.com/ec?token={MY_TOKEN}');
    $economic_calendar = $c->get_e_list(); 
} catch (Exception $e) {
    exit($e->getMessage());
}

谢谢!

标签: phpjsonclassfile-get-contents

解决方案


尽可能晚(或尽可能少)进行 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 在静态,逻辑在类实例)。


推荐阅读