Encapsulating the OpenWeatherMap API in a data source
1Introduction
In this tutorial, we'll look at how to create an object that can be used as a data source. For the example, we're going to make an object that interfaces with the OpenWeatherMap service API, enabling us to retrieve the current weather for any location (to be precise, the OpenWeatherMap API takes a latitude and longitude as parameters; we'll therefore use the Geocoding API to obtain the geographic coordinates of the requested city).
2Configuration
In the etc/temma.php configuration file, we'll add the definition of a rather special data source. As this is not a data source natively managed by Temma, we'll prefix the DSN with the name of the object to be used (in square brackets).
The DSN will take the form openweather://API_KEY
API_KEY being the API key provided by OpenWeatherMap.
Example configuration:
3Source code
Here's the code for our data source, which we'll save in the lib/OpenWeatherMap/Weather.php file:
- Lines 21 to 27: factory() method, called by Temma when the data source is created. This method interprets the DSN and calls the constructor.
- Lines 32 to 34: Constructor, used to create an instance of the object directly.
- Lines 43 to 72: get() method, which overrides the get() method of the parent \Temma\Base\Datasource object. This method can be used directly, but is also called automatically when read as an array.
- Lines 45 to 54: Connection to the Geocoding API, to obtain the latitude and longitude of the requested city.
- Lines 56 to 65: Connection to the OpenWeatherMap API, to obtain weather information from the latitude and longitude previously retrieved.
4Usage
In a controller, the data source named "meteo" in the configuration file is available by writing
$this->meteo
. Weather information can be retrieved by calling the get()
method or by using it as an array:
In another object, you need to use the dependency injection component:
The retrieved data is stored in an associative array: