あるユーザーが公開しているプログラミングを参考にして
オブジェクト化してみた。
参考にしたサイトのリンクは下記になります。
phpでapiを切りの良い時刻までキャッシュする
尚、動作環境はPHP5.6以上になります、と言いつつ
動作テストは行っていないので、もしかしたらエラーで動かないかも?
動作内容はJSONファイルの更新時間( hour )と
サーバの 時間 ( hour ) を比べ差異があれば
APIを呼び出し結果をJSONファイルとして上書き保存します。
そのため、一時間に一回だけ更新処理が走ります。
(※CRONで設定していれば)
結果がJSONで返ってこない場合などは可変して頂いて構いません。
もともと自分の案でもないので…。
PHPファイルのダウンロードはこちらから
https://zip358.com/tool/timeKeeper/timeKeeper.zip
ソースコードはこちらになります(* ̄(エ) ̄*)
<?php
class timeKeeper{
public static $json_filename = "abc.json";
public static $json_api_url = "https://example.com/api/?v=1.333";
public static function judge(){
$server_timestamp = time();
$server_time = date('Y/m/d H',$server_timestamp);
$json_timestamp = filemtime(self::$json_filename);
$json_time = date('Y/m/d H',$json_timestamp);
return $server_time === $json_time ? true : false;
}
public static function api_run($opts=null){
if(is_null($opts))return false;
$context = stream_context_create($opts);
$json = file_get_contents(self::$json_api_url, false, $context);
$fp = fopen(self::$json_filename, "w");
fwrite($fp,$json);
fclose($fp);
return self::json_load();
}
public static function json_load(){
$json = file_get_contents(self::$json_filename);
return json_decode($json, true);
}
public static function check(){
if(file_exists(self::$json_filename)){
return self::judge();
}
return false;
}
}
///使用例
if(timeKeeper::check()){
$json = timeKeeper::json_load();
}else{
$opts = array(
"http"=>array(
"method" => "POST",
"header" => "User-Agent: php"
)
);
$json = timeKeeper::api_run($opts);
}