Cache.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. /**
  3. * OpenWeatherMap-PHP-API — A php api to parse weather data from http://www.OpenWeatherMap.org .
  4. *
  5. * @license MIT
  6. *
  7. * Please see the LICENSE file distributed with this source code for further
  8. * information regarding copyright and licensing.
  9. *
  10. * Please visit the following links to read about the usage policies and the license of
  11. * OpenWeatherMap before using this class:
  12. *
  13. * @see http://www.OpenWeatherMap.org
  14. * @see http://www.OpenWeatherMap.org/terms
  15. * @see http://openweathermap.org/appid
  16. */
  17. use Cmfcmf\OpenWeatherMap;
  18. use Cmfcmf\OpenWeatherMap\AbstractCache;
  19. require_once __DIR__ . '/bootstrap.php';
  20. /**
  21. * Example cache implementation.
  22. *
  23. * @ignore
  24. */
  25. class ExampleCache extends AbstractCache
  26. {
  27. protected $tmp;
  28. public function __construct()
  29. {
  30. $this->tmp = sys_get_temp_dir();
  31. }
  32. private function urlToPath($url)
  33. {
  34. $dir = $this->tmp . DIRECTORY_SEPARATOR . "OpenWeatherMapPHPAPI";
  35. if (!is_dir($dir)) {
  36. mkdir($dir);
  37. }
  38. $path = $dir . DIRECTORY_SEPARATOR . md5($url);
  39. return $path;
  40. }
  41. /**
  42. * @inheritdoc
  43. */
  44. public function isCached($url)
  45. {
  46. $path = $this->urlToPath($url);
  47. if (!file_exists($path) || filectime($path) + $this->seconds < time()) {
  48. echo "Weather data is NOT cached!\n";
  49. return false;
  50. }
  51. echo "Weather data is cached!\n";
  52. return true;
  53. }
  54. /**
  55. * @inheritdoc
  56. */
  57. public function getCached($url)
  58. {
  59. return file_get_contents($this->urlToPath($url));
  60. }
  61. /**
  62. * @inheritdoc
  63. */
  64. public function setCached($url, $content)
  65. {
  66. file_put_contents($this->urlToPath($url), $content);
  67. }
  68. /**
  69. * @inheritdoc
  70. */
  71. public function setTempPath($path)
  72. {
  73. if (!is_dir($path)) {
  74. mkdir($path);
  75. }
  76. $this->tmp = $path;
  77. }
  78. }
  79. // Language of data (try your own language here!):
  80. $lang = 'de';
  81. // Units (can be 'metric' or 'imperial' [default]):
  82. $units = 'metric';
  83. // Example 1: Use your own cache implementation. Cache for 10 seconds only in this example.
  84. $cache = new ExampleCache();
  85. $cache->setTempPath(__DIR__.'/temps');
  86. $owm = new OpenWeatherMap($myApiKey, null, $cache, 10);
  87. $weather = $owm->getWeather('Berlin', $units, $lang);
  88. echo "EXAMPLE 1<hr />\n\n\n";
  89. echo $weather->temperature;