Skip to content

Commit c2db0e2

Browse files
committed
Refactored and fixed cache, closes #9, thanks @goranata for reporting!
1 parent 02bf37c commit c2db0e2

File tree

3 files changed

+51
-51
lines changed

3 files changed

+51
-51
lines changed

Cmfcmf/OpenWeatherMap.php

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
namespace Cmfcmf;
1818

19+
use Cmfcmf\OpenWeatherMap\AbstractCache;
1920
use Cmfcmf\OpenWeatherMap\CurrentWeather;
2021
use Cmfcmf\OpenWeatherMap\Exception as OWMException;
2122
use Cmfcmf\OpenWeatherMap\Fetcher\CurlFetcher;
@@ -77,20 +78,19 @@ class OpenWeatherMap
7778
* Constructs the OpenWeatherMap object.
7879
*
7980
* @param null|FetcherInterface $fetcher The interface to fetch the data from OpenWeatherMap. Defaults to
80-
* CurlFetcher() if if cURL is available. Otherwise defaults to
81+
* CurlFetcher() if cURL is available. Otherwise defaults to
8182
* FileGetContentsFetcher() using 'file_get_contents()'.
82-
* @param bool|string $cacheClass If set to false, caching is disabled. If this is a valid class
83-
* extending Cmfcmf\OpenWeatherMap\Util\Cache, caching will be enabled.
84-
* Default false.
83+
* @param bool|string $cacheClass If set to false, caching is disabled. Otherwise this must be a class
84+
* extending AbstractCache. Defaults to false.
8585
* @param int $seconds How long weather data shall be cached. Default 10 minutes.
8686
*
8787
* @throws \Exception If $cache is neither false nor a valid callable extending Cmfcmf\OpenWeatherMap\Util\Cache.
8888
* @api
8989
*/
9090
public function __construct($fetcher = null, $cacheClass = false, $seconds = 600)
9191
{
92-
if ($cacheClass !== false && !class_exists($cacheClass)) {
93-
throw new \Exception("Class $cacheClass does not exist.");
92+
if ($cacheClass !== false && !($cacheClass instanceof AbstractCache)) {
93+
throw new \Exception("The cache class must implement the FetcherInterface!");
9494
}
9595
if (!is_numeric($seconds)) {
9696
throw new \Exception("\$seconds must be numeric.");
@@ -348,7 +348,7 @@ public function getRawWeatherData($query, $units = 'imperial', $lang = 'en', $ap
348348
{
349349
$url = $this->buildUrl($query, $units, $lang, $appid, $mode, $this->weatherUrl);
350350

351-
return $this->cacheOrFetchResult('weather', $query, $units, $lang, $mode, $url);
351+
return $this->cacheOrFetchResult($url);
352352
}
353353

354354
/**
@@ -394,7 +394,7 @@ public function getRawHourlyForecastData($query, $units = 'imperial', $lang = 'e
394394
{
395395
$url = $this->buildUrl($query, $units, $lang, $appid, $mode, $this->weatherHourlyForecastUrl);
396396

397-
return $this->cacheOrFetchResult('hourlyForecast', $query, $units, $lang, $mode, $url);
397+
return $this->cacheOrFetchResult($url);
398398
}
399399

400400
/**
@@ -445,7 +445,7 @@ public function getRawDailyForecastData($query, $units = 'imperial', $lang = 'en
445445
}
446446
$url = $this->buildUrl($query, $units, $lang, $appid, $mode, $this->weatherDailyForecastUrl) . "&cnt=$cnt";
447447

448-
return $this->cacheOrFetchResult('dailyForecast', $query, $units, $lang, $mode, $url);
448+
return $this->cacheOrFetchResult($url);
449449
}
450450

451451
/**
@@ -515,7 +515,7 @@ public function getRawWeatherHistory($query, \DateTime $start, $endOrCount = 1,
515515
$queryUrl .= "&APPID=$appid";
516516
}
517517

518-
return $this->cacheOrFetchResult('weatherHistory', $query, $units, $lang, $type, $queryUrl);
518+
return $this->cacheOrFetchResult($queryUrl);
519519
}
520520

521521
/**
@@ -532,17 +532,17 @@ public function getRawWeatherHistory($query, \DateTime $start, $endOrCount = 1,
532532
*
533533
* @internal
534534
*/
535-
private function cacheOrFetchResult($type, $query, $units, $lang, $mode, $url)
535+
private function cacheOrFetchResult($url)
536536
{
537537
if ($this->cacheClass !== false) {
538538
/** @var \Cmfcmf\OpenWeatherMap\AbstractCache $cache */
539-
$cache = new $this->cacheClass;
539+
$cache = $this->cacheClass;
540540
$cache->setSeconds($this->seconds);
541-
if ($cache->isCached($type, $query, $units, $lang, $mode)) {
542-
return $cache->getCached($type, $query, $units, $lang, $mode);
541+
if ($cache->isCached($url)) {
542+
return $cache->getCached($url);
543543
}
544544
$result = $this->fetcher->fetch($url);
545-
$cache->setCached($type, $result, $query, $units, $lang, $mode);
545+
$cache->setCached($url, $result);
546546
} else {
547547
$result = $this->fetcher->fetch($url);
548548
}

Cmfcmf/OpenWeatherMap/AbstractCache.php

Lines changed: 9 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -29,46 +29,32 @@ abstract class AbstractCache
2929
/**
3030
* Checks whether a cached weather data is available.
3131
*
32-
* @param string $type The type of the cached data. Can be either 'weather', 'hourlyForecast' or 'dailyForecast'.
33-
* @param array|int|string $query The query parameters used.
34-
* @param string $units The units requested.
35-
* @param string $lang The language requested.
36-
* @param string $mode The mode requested ('xml' or'json').
32+
* @param string $url The unique url of the cached content.
3733
*
38-
* @return \DateTime|bool A \DateTime object containing the time when the weather information was last updated, false if no
39-
* cached information is available.
34+
* @return bool False if no cached information is available, otherwise true.
4035
*
41-
* @note This is not the time when the weather was cached, but the {@link Weather::$lastUpdate} value of the cached weather.
42-
* @note You need to check here if a cached result is outdated. Return false in that case.
36+
* You need to check if a cached result is outdated here. Return false in that case.
4337
*/
44-
public abstract function isCached($type, $query, $units, $lang, $mode);
38+
abstract public function isCached($url);
4539

4640
/**
4741
* Returns cached weather data.
4842
*
49-
* @param string $type The type of the cached data. Can be either 'weather', 'hourlyForecast' or 'dailyForecast'.
50-
* @param array|int|string $query The query parameters used.
51-
* @param string $units The units requested.
52-
* @param string $lang The language requested.
53-
* @param string $mode The mode requested ('xml' or'json').
43+
* @param string $url The unique url of the cached content.
5444
*
5545
* @return string|bool The cached data if it exists, false otherwise.
5646
*/
57-
public abstract function getCached($type, $query, $units, $lang, $mode);
47+
abstract public function getCached($url);
5848

5949
/**
6050
* Saves cached weather data.
6151
*
62-
* @param string $type The type of the cached data. Can be either 'weather', 'hourlyForecast' or 'dailyForecast'.
63-
* @param string $content The weather data to cache.
64-
* @param array|int|string $query The query parameters used.
65-
* @param string $units The units requested.
66-
* @param string $lang The language requested.
67-
* @param string $mode The mode requested ('xml' or'json').
52+
* @param string $url The unique url of the cached content.
53+
* @param string $content The weather data to cache.
6854
*
6955
* @return bool True on success, false on failure.
7056
*/
71-
public abstract function setCached($type, $content, $query, $units, $lang, $mode);
57+
abstract public function setCached($url, $content);
7258

7359
/**
7460
* Set after how much seconds the cache shall expire.

Examples/Cache.php

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,34 +32,48 @@
3232
*/
3333
class ExampleCache extends AbstractCache
3434
{
35+
private function urlToPath($url)
36+
{
37+
$tmp = sys_get_temp_dir();
38+
$dir = $tmp . DIRECTORY_SEPARATOR . "OpenWeatherMapPHPAPI";
39+
if (!is_dir($dir)) {
40+
mkdir($dir);
41+
}
42+
43+
$path = $dir . DIRECTORY_SEPARATOR . md5($url);
44+
45+
return $path;
46+
}
47+
3548
/**
3649
* @inheritdoc
3750
*/
38-
public function isCached($type, $query, $units, $lang, $mode)
51+
public function isCached($url)
3952
{
40-
echo "Checking cache for $type $query $units $lang $mode …<br />";
53+
$path = $this->urlToPath($url);
54+
if (!file_exists($path) || filectime($path) + $this->seconds < time()) {
55+
echo "Weather data is NOT cached!\n";
56+
return false;
57+
}
4158

42-
return false;
59+
echo "Weather data is cached!\n";
60+
return true;
4361
}
4462

4563
/**
4664
* @inheritdoc
4765
*/
48-
public function getCached($type, $query, $units, $lang, $mode)
66+
public function getCached($url)
4967
{
50-
echo "Get cache for $type $query $units $lang $mode …<br />";
51-
52-
return false;
68+
return file_get_contents($this->urlToPath($url));
5369
}
5470

5571
/**
5672
* @inheritdoc
5773
*/
58-
public function setCached($type, $content, $query, $units, $lang, $mode)
74+
public function setCached($url, $content)
5975
{
60-
echo "Set cache for $type $query $units $lang $mode … ({$this->seconds} seconds)<br />";
61-
62-
return false;
76+
file_put_contents($this->urlToPath($url), $content);
6377
}
6478
}
6579

@@ -69,8 +83,8 @@ public function setCached($type, $content, $query, $units, $lang, $mode)
6983
// Units (can be 'metric' or 'imperial' [default]):
7084
$units = 'metric';
7185

72-
// Example 1: Use your own cache implementation. See the example_cache file.
73-
$owm = new OpenWeatherMap('ExampleCache', 100);
86+
// Example 1: Use your own cache implementation. Cache for 10 seconds only in this example.
87+
$owm = new OpenWeatherMap(null, new ExampleCache(), 10);
7488

7589
$weather = $owm->getWeather('Berlin', $units, $lang);
7690
echo "EXAMPLE 1<hr />\n\n\n";

0 commit comments

Comments
 (0)