dive-be/laravel-geo
Composer 安装命令:
composer require dive-be/laravel-geo
包简介
Translate IP addresses into geo locations
README 文档
README
🌍 - Translate IP addresses into geo locations
This package will assist you in grabbing a visitor's country.
What problem does this package solve?
Depending on the context of your application, you may want to display content tailored for a specific country/region of the visitor. This package will help with providing a sensible default using IP addresses if it is a first time visit for a user.
Installation
You can install the package via composer:
composer require dive-be/laravel-geo
You will also need to install GeoIP2 if you're planning to use their services:
composer require geoip2/geoip2
You can publish the config file with:
php artisan geo:install
This is the content of the config file:
return [ /** * IP address translations can be cached to improve successive lookup times. */ 'cache' => [ 'enabled' => false, /** * Address translations are tagged to only clear them when a clear command is run. * Not supported by the "file", "database" and "dynamodb" cache drivers. */ 'tag' => 'dive-geo-location', /** * Time-to-live in seconds. */ 'ttl' => 3600, ], /** * Detectors are classes responsible for detecting the geo location of a given IP address. * * Supported drivers: * - "static" (always translates to the fallback country) * - "maxmind_db" (GeoIP2/GeoLite2 Databases) * - "maxmind_web" (GeoIP2 Precision Web Services) * - "ip2c" (IP 2 Country free web service) */ 'detectors' => [ 'driver' => env('GEO_DETECTORS_DRIVER', 'static'), 'ip2c' => [ 'endpoint' => 'https://api.ip2country.info/ip', ], 'maxmind_db' => [ 'database_path' => storage_path('app/geoip2.mmdb'), 'license_key' => env('GEO_DETECTORS_MAXMIND_DB_LICENSE_KEY'), 'url' => 'https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-Country&license_key=%s&suffix=tar.gz', ], 'maxmind_web' => [ 'account_id' => env('GEO_DETECTORS_MAXMIND_WEB_ACCOUNT_ID'), 'license_key' => env('GEO_DETECTORS_MAXMIND_WEB_LICENSE_KEY'), ], ], /** * A valid ISO alpha-2 country code. * Used when an IP address cannot be translated. */ 'fallback' => 'BE', 'repos' => [ 'cookie' => [ 'name' => 'geo', // The cookie's name when set on the users' browsers ], ], /** * The valid FQCN of your custom transformer. * When set, values retrieved from the repository will be transformed first using this class. */ 'transformer' => null, ];
Usage
First, you will have to decide which service to use.
Detectors
When you've decided, set the GEO_DETECTORS_DRIVER environment variable to the correct value.
Refer to the configuration file for the right values.
GeoIP2 Databases
- Generate a license key
- Set the
GEO_DETECTORS_MAXMIND_DB_LICENSE_KEYenvironment variable to your license key
Auto updating local database
IP address ranges tend to become out of date over time. Therefore, this package also provides a convenient update command which you can schedule to run once a week to keep everything fresh.
// Console\Kernel.php protected function schedule(Schedule $schedule) { $schedule->command('geo:update')->weekly(); }
Only applicable if using MaxMind's GeoIP2 Databases.
GeoIP2 Precision Web Services
- Get
account_id&license_key - Set the
GEO_DETECTORS_MAXMIND_WEB_ACCOUNT_ID&GEO_DETECTORS_MAXMIND_WEB_LICENSE_KEYenvironment variables
IP 2 Country
This is a free service. You don't have to configure anything.
Note: it is strongly recommended to enable caching for this driver.
Static
The static driver is meant for usage during local development and testing. You should not use it in any other environment as it is always going to return the fallback value.
Detecting a visitor's geo location
Add the DetectGeoLocation (or alias geo) middleware to your kernel's web middleware stack and you are good to go.
If your app is behind a proxy/load balancer, make sure DetectGeoLocation is defined after TrustProxies.
'web' => [ // omitted for brevity \Illuminate\Routing\Middleware\SubstituteBindings::class, \Dive\Geo\Middleware\DetectGeoLocation::class, ],
Retrieving the detected country 🗺
There are multiple ways to retrieve the detected ISO alpha-2 country code.
Facade
use Dive\Geo\Facades\Geo; Geo::get();
or using the alias
use Geo; Geo::get();
Helper
geo()->get()
Dependency injection
use Dive\Geo\Contracts\Repository; public function __invoke(Repository $geo) { $geo->get(); }
Transforming the detected geo location 🔷
It is a high probability that you'd like to transform the ISO alpha-2 country code into your own Eloquent model or value object
after calling get on the repository class. You may define your own CountryTransformer which implements the Transformer interface
and simply returns the desired object.
e.g.
namespace App\Transformers; use App\Models\Country; use Dive\Geo\Contracts\Transformer; class CountryTransformer implements Transformer { public function transform(string $iso): Country { return Country::findByIso($iso); } }
After defining the class, make sure to provide the FQCN in the configuration file.
'transformer' => App\Transformers\CountryTransformer::class,
Overwriting existing country ✍🏼
At any point in time, you may overwrite the detected country code. Simply call:
geo('TR'); // helper Geo::put('TR'); // facade $geo->put('TR'); // injected
Clearing the cache 🔥
When enabled, the translated addresses will be held in cache for a certain amount of time defined in the configuration file. If you'd like to wipe these translations, use the command:
php artisan geo:clear
Note: the cache driver must support tagging or else everything will be cleared when the command above is run.
Extending the detectors 👣
If the default drivers do not fulfill your needs, you may extend the DetectorManager with your own custom drivers:
use Dive\Geo\Facades\Detector; Detector::extend('ipapi', function () { return new IPApiDetector(...); });
Testing 🔎
This package offers fake implementations of the Repository & Detector contracts so you can make assertions in your unit tests and make sure you ship that bug-free code 💪. Just call fake on either of them and you're set:
use Dive\Geo\Facades\Detector; use Dive\Geo\Facades\Geo; Detector::fake(); Geo::fake();
Testing (package)
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email oss@dive.be instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
dive-be/laravel-geo 适用场景与选型建议
dive-be/laravel-geo 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11.02k 次下载、GitHub Stars 达 37, 最近一次更新时间为 2021 年 04 月 07 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「geo」 「laravel」 「location」 「iso」 「dive」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 dive-be/laravel-geo 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 dive-be/laravel-geo 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 dive-be/laravel-geo 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Show geo marker on a mapbox map
Show geo shape on a mapbox map with drawing capabilities
The official PHP library for apiip.net that allowing customers to automate IP address validation and geolocation lookup in websites, applications and back-office system. Visit our API docs at https://apiip.net/documentation
A Symfony2 Bundle to handle geographic location of your entities
Add a weather widget to Flarum
A modern, feature-rich Laravel package for managing addresses with geocoding, validation, caching, and spatial operations. Perfect for e-commerce, CRM systems, and any application requiring robust address management.
统计信息
- 总下载量: 11.02k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 37
- 点击次数: 7
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-04-07
