public function loadForecast()
 {
     //Open a handle to the DB
     $dbh = db_connect();
     //Check the DB for a cached forecast
     $where = array('lat' => $this->lat, 'lon' => $this->lon);
     $cache = db_fetchForecast($dbh, $where);
     $forecast = $cache['json'];
     $refresh = false;
     //If no cache exists, refresh
     if ($cache == null) {
         $refresh = true;
     }
     //If  freshness is older than threshold, refresh
     if ($cache != null) {
         $cacheFreshness = new DateTime($cache['fresh']);
         $now = new DateTime();
         if ($now > $cacheFreshness) {
             $refresh = true;
         }
     }
     //If a refresh is needed, pull fresh data, determine its fresh-til DateTime, and push it to the DB
     if ($refresh == true) {
         $forecast = $this->fetchForecast();
         $freshUntil = new DateTime();
         $threshold = new DateInterval('PT' . WEATHER_CACHE_MINUTES . 'M');
         //Yeah, I hate it too.
         $freshUntil->add($threshold);
         $what = array('lat' => $this->lat, 'lon' => $this->lon, 'fresh' => $freshUntil->format('Y-m-d H:i:s'), 'json' => $forecast);
         db_updateForecast($dbh, $what);
     }
     //Return either the cached or fresh forecast
     return $forecast;
 }
示例#2
0
function db_updateForecast($dbh, $what)
{
    $exists = db_fetchForecast($dbh, $what);
    if ($exists == null) {
        db_insertForecast($dbh, $what);
        return;
    }
    $stmt = $dbh->prepare("\n\t\tUPDATE `weather_cache`\n\t\tSET\n\t\t`fresh` = :fresh,\n\t\t`json` = :json\n\t\tWHERE `lat` LIKE :lat\n\t\tAND `lon` LIKE :lon;\n\t");
    $stmt->bindValue(':lat', $what['lat']);
    $stmt->bindValue(':lon', $what['lon']);
    $stmt->bindValue(':fresh', $what['fresh']);
    $stmt->bindValue(':json', $what['json']);
    $stmt->execute();
}