php - 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());
}
谢谢!
解决方案
尽可能晚(或尽可能少)进行 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 在静态,逻辑在类实例)。
推荐阅读
- java - 如何在 java 15 文本块中保留尾随空格
- oracle - 使用 BLOB 数据类型 Vuejs 将输入图像文件上传到数据库
- github - 从 Terraform 云功能连接到 Enterprise GitHub
- drop-down-menu - 如何防止在移动设备上单击时关闭 Bootstrap 4.6 下拉菜单
- python - 奇怪的线条行为 matplotlib 3D Plot
- c++ - Qt 打开带有上下文菜单条目/shell 扩展的文件 [Windows]
- java - JSP 代码行导致文本在一个地方显示为超链接,但在另一个地方显示为密文文本
- spring-boot - 验证 Auth0 令牌 - Spring Security
- database - 具有大表和许多更新的 Autovacuum postgresql 11
- django - 如何使用 PostgreSQL DB 在 Django Rest Framework 中关联两个没有外键的 Django 模型