gpt4 book ai didi

PHP:在类构造函数中使用 file_get_contents() 是一种不好的做法吗?

转载 作者:行者123 更新时间:2023-12-02 00:52:25 25 4
gpt4 key购买 nike

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

哪种做法更好,为什么?

到目前为止,这是我的类(class) (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());
}

谢谢!

最佳答案

几乎总是让 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 在静态,逻辑在类实例)。

关于PHP:在类构造函数中使用 file_get_contents() 是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56621107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com