stevebauman/location
Composer 安装命令:
composer require stevebauman/location
包简介
Retrieve a user's location by their IP Address
README 文档
README
Retrieve a visitor's location from their IP address using various services (online & local).
Index
Requirements
- PHP >= 8.1
- Laravel >= 8.0
Installation
Install location using composer require:
composer require stevebauman/location
Publish the configuration file (this will create a location.php file inside the config directory):
php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"
Usage
Retrieve a client's location
use Stevebauman\Location\Facades\Location; if ($position = Location::get()) { // Successfully retrieved position. echo $position->countryName; } else { // Failed retrieving position. }
Important:
- This method retrieves the user's IP address via
request()->ip().- In the default configuration,
testing.enabledis active, the returned IP address is in the USA. Disable it to get the client's real IP address.
Retrieve the location of a specific IP address
$position = Location::get('192.168.1.1');
Testing
You may call Location::fake with an array of IP address patterns and their expected positions to fake the location of an IP address:
use Stevebauman\Location\Position; use Stevebauman\Location\Facades\Location; Location::fake([ '127.0.0.1' => Position::make([ 'countryName' => 'United States', 'countryCode' => 'US', // ... ]) ]); // Somewhere in your application... $position = Location::get('127.0.0.1'); // Position
If you prefer, you may use an asterisk to return the same position for any IP address that is given:
Location::fake([ '*' => Position::make([ 'countryName' => 'United States', 'countryCode' => 'US', // ... ]) ]); $position = Location::get($anyIpAddress); // Position
If no expectations are given, or an expectation is not matched, Location::get will return false:
Location::fake(); Location::get($anyIpAddress); // false
If your application attempts to retrieve the location's of multiple IP addresses, you may provide multiple IP address expectation patterns:
Location::fake([ '127.0.0.1' => Position::make([ 'countryName' => 'United States', 'countryCode' => 'US', // ... ]), '192.168.1.1' => Position::make([ 'countryName' => 'Canada', 'countryCode' => 'CA', // ... ]), ]);
You may also use an asterisk to fake several IP patterns:
Location::fake([ '192.123.*.*' => Position::make([ 'countryName' => 'United States', 'countryCode' => 'US', // ... ]), '192.456.*.*' => Position::make([ 'countryName' => 'Canada', 'countryCode' => 'CA', // ... ]), ]);
Drivers
Available Drivers
Available drivers:
- IpApi - Default
- IpApiPro
- IpData
- IpInfo
- IpInfo Lite
- Kloudend
- GeoPlugin
- MaxMind
- Cloudflare
- IP2Location.io
Setting up MaxMind with a self-hosted database (optional)
It is encouraged to set up MaxMind as a fallback driver using a local database so that some location information is returned in the event of hitting a rate limit from the external web services.
To set up MaxMind to retrieve the user's location from your own server, you must:
- Create a maxmind account and sign in
- Click "Manage License Keys" from the profile menu dropdown
- Generate a new license key
- Copy the license key and save it into your
.envfile using theMAXMIND_LICENSE_KEYkey - Run
php artisan location:updateto download the latest.mmdbfile into yourdatabase/maxminddirectory - That's it, you're all set!
Note: Keep in mind, you'll need to update this file by running
location:updateon a regular basis to retrieve the most current information from your visitors.
Fallback Drivers
In the config file, you can specify as many fallback drivers as you wish. It is
recommended to configure the MaxMind driver with the local database .mmdb
file (mentioned above), so you are alwaysretrieving some generic location
information from the visitor.
If an exception occurs trying to grab a driver (such as a 400/500 error if the providers API changes), it will automatically use the next driver in line.
Creating your own drivers
To create your own driver, simply create a class in your application, and extend the abstract Driver:
namespace App\Location\Drivers; use Illuminate\Support\Fluent; use Illuminate\Support\Facades\Http; use Stevebauman\Location\Position; use Stevebauman\Location\Request; use Stevebauman\Location\Drivers\Driver; class MyDriver extends Driver { protected function process(Request $request): Fluent { $response = Http::get("https://driver-url.com", ['ip' => $request->getIp()]); return new Fluent($response->json()); } protected function hydrate(Position $position, Fluent $location): Position { $position->countryCode = $location->country_code; return $position; } }
Then, insert your driver class name into the configuration file:
// config/location.php 'driver' => App\Location\Drivers\MyDriver::class,
Upgrading from v6
In version 7, the codebase has been updated with strict PHP types,
updated PHP and Laravel version requirements, an updated Driver
structure, as well as a small configuration addition.
Configuration
In version 7, location drivers can now implement an Updatable interface
that allows them to be updated using the location:update command.
Currently, only the MaxMind driver supports this.
To update your configuration file to be able to download the latest
MaxMind database file automatically, insert the below url
configuration option in your config/location.php file:
// config/location.php
return [
'maxmind' => [
// ...
'local' => [
// ...
+ 'url' => sprintf('https://download.maxmind.com/app/geoip_download_by_token?edition_id=GeoLite2-City&license_key=%s&suffix=tar.gz', env('MAXMIND_LICENSE_KEY')),
],
],
];
Once done, you may execute the below artisan command to download the latest .mmdb file:
php artisan location:update
Drivers
In version 7, the codebase has been updated with strict PHP
types, updated PHP and Laravel version requirements,
and an updated Driver structure.
If you have created your own custom driver implementation,
you must update it to use the base Driver or HttpDriver class.
If you're fetching a location using an HTTP service, it
may be useful to extend the HttpDriver to reduce
the code you need to write:
namespace App\Location\Drivers; use Illuminate\Support\Fluent; use Stevebauman\Location\Position; - use Stevebauman\Location\Drivers\Driver; + use Stevebauman\Location\Drivers\HttpDriver; - class MyDriver extends Driver + class MyDriver extends HttpDriver { - public function url($ip) + public function url(string $ip): string; { return "http://driver-url.com?ip=$ip"; } - protected function process($ip) - { - return rescue(function () use ($ip) { - $response = json_decode(file_get_contents($this->url($ip)), true); - - return new Fluent($response); - }, $rescue = false); - } - protected function hydrate(Position $position, Fluent $location) + protected function hydrate(Position $position, Fluent $location): Position; { $position->countryCode = $location->country_code; return $position; } }
Versioning
Location is versioned under the Semantic Versioning guidelines as much as possible.
Releases will be numbered with the following format:
<major>.<minor>.<patch>
And constructed with the following guidelines:
- Breaking backward compatibility bumps the major and resets the minor and patch.
- New additions without breaking backward compatibility bumps the minor and resets the patch.
- Bug fixes and misc changes bumps the patch.
Minor versions are not maintained individually, and you're encouraged to upgrade through to the next minor version.
Major versions are maintained individually through separate branches.
stevebauman/location 适用场景与选型建议
stevebauman/location 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.52M 次下载、GitHub Stars 达 1.3k, 最近一次更新时间为 2014 年 05 月 06 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「geo」 「geoip」 「laravel」 「location」 「IP」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 stevebauman/location 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 stevebauman/location 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 stevebauman/location 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A GeoIP decorator/processor for monolog
Show geo marker on a mapbox map
Show geo shape on a mapbox map with drawing capabilities
Add a weather widget to Flarum
PHP GeoIP client
Laravel Geocode by address library
统计信息
- 总下载量: 8.52M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1309
- 点击次数: 25
- 依赖项目数: 76
- 推荐数: 1
其他信息
- 授权协议: MIT
- 更新时间: 2014-05-06