dotkernel/dot-geoip

基于 Maxmind 的 geoip2/geoip2 包的 DotKernel 组件,使用其免费的 GeoLite2 数据库来提供关于 IP 地址的地理详情。

3.7.2 2024-07-04 09:17 UTC

This package is auto-updated.

Last update: 2024-09-06 10:08:30 UTC


README

重要

dot-geoip 是 maxmind/GeoIP2-php 的封装

OSS Lifecycle

OSS Lifecycle PHP from Packagist (specify version)

GitHub issues GitHub forks GitHub stars GitHub license

Build Static

SymfonyInsight

安装

您可以通过运行以下命令来安装此库

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} 可以是以下值之一: asncitycountry

您可以通过运行以下命令一次性下载/更新所有 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
        }
    }
}