dotkernel / dot-geoip
基于 Maxmind 的 geoip2/geoip2 包的 DotKernel 组件,使用其免费的 GeoLite2 数据库来提供关于 IP 地址的地理详情。
Requires
- php: ~8.2.0 || ~8.3.0
- dotkernel/dot-cli: ^3.5
- geoip2/geoip2: ^3.0
- guzzlehttp/guzzle: ^7.8
- laminas/laminas-filter: ^2.34
- psr/container: ^1.1
- symfony/filesystem: ^7.0
Requires (Dev)
- laminas/laminas-coding-standard: ^2.5
- mikey179/vfsstream: ^1.6.7
- phpunit/phpunit: ^10.5
- vimeo/psalm: ^5.21
README
重要
dot-geoip 是 maxmind/GeoIP2-php 的封装
安装
您可以通过运行以下命令来安装此库
composer require dotkernel/dot-geoip
如果您的应用程序尚未使用它,上述命令还安装了 dotkernel/dot-cli。在这种情况下,请参阅它的 README 文件了解如何使用它。
将配置文件 vendor/dotkernel/dot-geoip/config/autoload/geoip.global.php
复制到您应用程序的 config/autoload
目录。
通过向您的应用程序的 config/config.php
文件添加以下行来注册库的 ConfigProvider
Dot\GeoIP\ConfigProvider::class,
通过向您的应用程序的 config/autoload/cli.global.php
文件中的 commands
键数组添加以下行来注册库的同步器命令
Dot\GeoIP\Command\GeoIpCommand::getDefaultName() => Dot\GeoIP\Command\GeoIpCommand::class,
管理 GeoLite2 数据库
您可以通过运行以下命令下载/更新特定的 GeoLite2 数据库
php bin/cli.php geoip:synchronize -d {DATABASE}
其中 {DATABASE} 可以是以下值之一: asn
、city
、country
。
您可以通过运行以下命令一次性下载/更新所有 GeoLite2 数据库
php bin/cli.php geoip:synchronize
输出应类似于以下内容,按行显示:数据库标识符
: 上一个构建日期时间
-> 当前构建日期时间
。
asn: n/a -> 2021-07-01 02:09:34
city: n/a -> 2021-07-01 02:09:20
country: n/a -> 2021-07-01 02:05:12
通过运行 php bin/cli.php help geoip:synchronize
获取此命令的帮助。
提示:如果您将同步器命令设置为 cronjob,可以添加 -q|--quiet
选项,并且它只有在发生错误时才会输出数据。
用法
以下是一个使用 DotGeoip 获取 IP 地址信息的示例实现。
<?php
declare(strict_types=1);
namespace Api\Example\Service;
use Dot\GeoIP\Service\LocationServiceInterface;
use Throwable;
/**
* Class ExampleService
* @package Api\Example\Service
*/
class ExampleService
{
protected LocationServiceInterface $locationService;
/**
* ExampleService constructor.
* @param LocationServiceInterface $locationService
*/
public function __construct(LocationServiceInterface $locationService)
{
$this->locationService = $locationService;
}
/**
* @param string $ipAddress
* @return object
*/
public function myMethod(string $ipAddress): object
{
try {
// You can use any of the below methods:
// Get CountryData which includes isEuMember, isoCode and name
return $this->locationService->getCountry($ipAddress);
// Get ContinentData which includes code and name
return $this->locationService->getContinent($ipAddress);
// Get OrganizationData which includes asn and name
return $this->locationService->getOrganization($ipAddress);
// Get LocationData which includes all of the above + estimated coordinates + timezone
return $this->locationService->getLocation($ipAddress);
} catch (Throwable $exception) {
// handle errors
}
}
}