- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个用 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/
如果您想分享更多信息,可以在这里找到整个资源 指针: https://github.com/sergiotapia/DreamInCode.Net 基本上,我的API将为其他开发人员提供
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 5 年前。 Improve this qu
我不是 SCM 工具的经验丰富的用户,尽管我确信它们的用处,当然。 我在以前的工作中使用了一些不起眼的商业工具,在当前的工作中使用了 Perforce,并在我的小型个人项目中使用了 TortoiseS
所以我想知道一些我应该避免在 javascript 中做的事情以获得良好的 SEO 排名。在我的下一个站点中,我将广泛使用 jquery 和 javascript,但不想牺牲 SEO。那么您认为我应该
基本上,我想知道什么是避免 future CSS 代码出现问题和混淆的最佳方法... 像这样命名 CSS 属性: div#content ul#navigation div.float-left (真
我是一名优秀的程序员,十分优秀!