]> git.mxchange.org Git - friendica-addons.git/blob - curweather/vendor/cmfcmf/openweathermap-php-api/Examples/Cache.php
added composer.json and needed libs
[friendica-addons.git] / curweather / vendor / cmfcmf / openweathermap-php-api / Examples / Cache.php
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
18 use Cmfcmf\OpenWeatherMap;
19 use Cmfcmf\OpenWeatherMap\AbstractCache;
20
21 if (file_exists('../vendor/autoload.php')) {
22     // Library is not part of a project. "composer install" was executed directly on this library's composer file.
23     require('../vendor/autoload.php');
24 } else {
25     // Library is part of a project.
26     /** @noinspection PhpIncludeInspection */
27     require('../../../autoload.php');
28 }
29
30 /**
31  * Example cache implementation.
32  *
33  * @ignore
34  */
35 class ExampleCache extends AbstractCache
36 {
37     private function urlToPath($url)
38     {
39         $tmp = sys_get_temp_dir();
40         $dir = $tmp . DIRECTORY_SEPARATOR . "OpenWeatherMapPHPAPI";
41         if (!is_dir($dir)) {
42             mkdir($dir);
43         }
44
45         $path = $dir . DIRECTORY_SEPARATOR . md5($url);
46
47         return $path;
48     }
49
50     /**
51      * @inheritdoc
52      */
53     public function isCached($url)
54     {
55         $path = $this->urlToPath($url);
56         if (!file_exists($path) || filectime($path) + $this->seconds < time()) {
57             echo "Weather data is NOT cached!\n";
58
59             return false;
60         }
61
62         echo "Weather data is cached!\n";
63
64         return true;
65     }
66
67     /**
68      * @inheritdoc
69      */
70     public function getCached($url)
71     {
72         return file_get_contents($this->urlToPath($url));
73     }
74
75     /**
76      * @inheritdoc
77      */
78     public function setCached($url, $content)
79     {
80         file_put_contents($this->urlToPath($url), $content);
81     }
82 }
83
84 // Language of data (try your own language here!):
85 $lang = 'de';
86
87 // Units (can be 'metric' or 'imperial' [default]):
88 $units = 'metric';
89
90 // Example 1: Use your own cache implementation. Cache for 10 seconds only in this example.
91 $owm = new OpenWeatherMap(null, new ExampleCache(), 10);
92
93 $weather = $owm->getWeather('Berlin', $units, $lang);
94 echo "EXAMPLE 1<hr />\n\n\n";
95 echo $weather->temperature;