keythkatz / datagovsg
Data.gov.sg 辅助工具
Requires
- php: ^7.2
- guzzlehttp/guzzle: ^6.3.3
Requires (Dev)
- phpunit/phpunit: ^7
This package is auto-updated.
Last update: 2021-07-06 12:44:02 UTC
README
DataGovSg-php
data.gov.sg 的 Composer 软件包
安装
composer require keythkatz/datagovsg
使用
$datagov = new \KeythKatz\DataGovSg\DataGovSg(); // Fetch data from a supported dataset $psi = $datagov->getPsi(); // Access data with helper methods echo $psi->getPsiTwentyFourHourly("national"); // Alternatively, access data directly, according to the same structure in JSON echo $psi->items[0]->readings->psi_twenty_four_hourly->national;
支持的数据集
要实现自己的数据集,请参阅实现自己的数据集
PSI
getPsi(\DateTime $date = null, bool $useTime = false)
参数
如果 $date
为 null,则不使用任何参数,API 将返回最新的读数。
如果 $useTime
为 false,则使用 API 中的 date
字段,并忽略提供的时间。否则,使用 date_time
。
辅助方法
数据集中可用的每个读数都使用 camelCase 实现。例如,数据 so2_twenty_four_hourly
可用为 $psi->getSo2TwentyFourHourly($region)
,其中 $region
在 ["national", "north", "south", "east", "west", "central"]
中。如果有多个时间提供,将返回第一个。
PM2.5
getPm25(\DateTime $date = null, bool $useTime = false)
参数
如果 $date
为 null,则不使用任何参数,API 将返回最新的读数。
如果 $useTime
为 false,则使用 API 中的 date
字段,并忽略提供的时间。否则,使用 date_time
。
辅助方法
数据集中可用的每个读数都使用 camelCase 实现。例如,数据 pm_25
可用为 $pm25->getPm25($region)
,其中 $region
在 ["north", "south", "east", "west", "central"]
中。如果有多个时间提供,将返回第一个。
实现自己的数据集
此软件包基于所有数据集返回 JSON 格式数据的假设。提供了带有辅助方法的抽象类 \KeythKatz\DataGovSg\Dataset\Dataset
。
通过您的新的数据集扩展它,使用完整的 API 路径覆盖 protected static $path
,并实现 __construct
。此外,您可能还想包括对常用数据的辅助方法。以下是一个示例:
class Pm25 extends \KeythKatz\DataGovSg\Dataset\Dataset { // Override this with the path to the dataset protected static $path = "/v1/environment/pm25"; public function __construct(\DateTime $date = null, bool $useTime = false) { if ($date !== null) { if (!$useTime) { $dateString = $date->format("Y-m-d"); // Added parameters will be sent as a querystring $this->addParameter("date", $dateString); } else { $dateString = $date->format("c"); // Added parameters will be sent as a querystring $this->addParameter("date_time", $dateString); } } // Makes a query and pulls the results into itself. $this->populateData(); } // Helper methods for commonly accessed data /** * Get the reading from the first item in the fetched data. * @param string $region Region of the data. Must match what is available on the API. * @return int */ public function getPm25OneHourly(string $region): int { return $this->items[0]->readings->pm25_one_hourly->$region; } }