abivia / geocoding
地理编码支持。
2.1.0
2024-02-04 04:30 UTC
Requires
- php: ^8.1
- ext-curl: *
- abivia/cogs: ^2
- mlocati/ip-lib: ^1
Requires (Dev)
- phpunit/phpunit: ^9.5
README
Abivia地理编码库提供了一个缓存接口,用于访问ipinfo.io和ipstack.com提供的IP地址查询API。该库支持IPv4和IPv6地址,并设计用于无缝支持其他IP地址地理编码服务。
要求
地理编码需要
- PHP 8.1或更高版本
- ext-curl以执行API调用
- abivia/cogs以支持地址
- mlocati/ip-lib以支持IP地址
PHP不需要构建IPv6支持。
安装
通过composer
composer require abivia/geocoding
缓存
地理编码附带两个专为轻量级使用设计的缓存处理程序。数组缓存将保留当前请求(或会话变量中存储的会话)的生命周期内的查询结果。文件缓存将缓存数据存储在文本文件中。两者都不提供对并发请求的支持。
应用程序可以通过符合CacheHandler接口来创建持久缓存。缓存支持不同缓存时间以用于查询命中和查询未命中。在文件缓存中,默认的命中缓存时间为七天,未命中缓存时间为一小时。
示例用法
use Abivia\Geocode\Geocoder; use Abivia\Geocode\LookupService\IpInfoApi; $geocoder = new Geocoder(IpInfoApi::make()); $info = $geocoder->lookup('4.4.4.4'); echo $info->getLatitude() . ', ' . $info->getLongitude();
地理编码器使用GeocodeResult接口标准化不同服务的输出,但应用程序可以通过GeocodeResult::data()方法检索服务的响应,以访问扩展信息。
使用文件缓存
use Abivia\Geocode\CacheHandler\FileCache; use Abivia\Geocode\Geocoder; use Abivia\Geocode\LookupService\IpInfoApi; // Get a cache and set the cache time for a hit to six hours $cache = new FileCache('mycache.json'); $cache->hitCacheTime(6 * 3600); $geocoder = new Geocoder(IpInfoApi::make(), $cache); $info = $geocoder->lookup('4.4.4.4'); echo $info->getLatitude() . ', ' . $info->getLongitude();
子网查询
从地理定位的角度来看,IPv4地址的前24位和IPv6地址的前48位对于大多数情况是有效的。地理编码提供了一个"子网"查询,将返回v4或v6范围内的最后查询结果。这可以减少查询服务的查询次数,提高性能,并在付费服务的情况下降低成本。
子网示例
use Abivia\Geocode\Geocoder; use Abivia\Geocode\LookupService\IpInfoApi; $geocoder = new Geocoder(IpInfoApi::make()); // Assume 4.4.4.4 is not currently cached. This will cause the service to be queried. $info = $geocoder->lookupSubnet('4.4.4.4'); echo $info->getLatitude() . ', ' . $info->getLongitude(); // This query will return the cached data for 4.4.4.4 $info2 = $geocoder->lookupSubnet('4.4.4.8');
欢迎捐赠
如果您从地理编码中获得了一些东西,您可以使用Liberapay以任何金额赞助我们 。Liberapay本身是通过捐赠运行的,并且不收取除银行费用以外的任何费用。