我最近須要一個用戶地域檢測來設置用戶的默認區域和貨幣。由 Daniel Stainback 建立的 torann/geoip 很好地知足爲Laravel 5 項目提供 GeoIP 服務的要求。laravel
這個 Laravel GeoIP 包支持一些服務,包括默認的 ip-api.com 服務, 一個可下載的 Maxmind 數據庫和 Maxmind API。你也能夠經過這個配置輕鬆地增長一個通用的服務。git
這個包的基本使用是引用 geoip()
幫助函數,可選擇性傳遞 IP 地址參數。下面是一個基於 IP 地址的地址對象的例子:github
\Torann\GeoIP\Location { #attributes:array [ 'ip' => '232.223.11.11', 'iso_code' => 'US', 'country' => 'United States', 'city' => 'New Haven', 'state' => 'CT', 'state_name' => 'Connecticut', 'postal_code' => '06510', 'lat' => 41.28, 'lon' => -72.88, 'timezone' => 'America/New_York', 'continent' => 'NA', 'currency' => 'USD', 'default' => false, ] }
正如你所看到的,地址對象包含一些地域信息,有助於決定用戶的貨幣,時區和國家 ISO 代碼。數據庫
若是目標地址沒有找到,可以使用一份可配置的備用地址代替,這時 default
參數被設置爲 true
。你能夠覆蓋默認設置,默認配置以下所示:api
'default_location' => [ 'ip' => '127.0.0.0', 'iso_code' => 'US', 'country' => 'United States', 'city' => 'New Haven', 'state' => 'CT', 'state_name' => 'Connecticut', 'postal_code' => '06510', 'lat' => 41.31, 'lon' => -72.92, 'timezone' => 'America/New_York', 'continent' => 'NA', 'default' => true, 'currency' => 'USD', ],
在 Github 官方地址 上查看包的源代碼,閱讀 文檔 有助於你使用這個包。函數
更多現代化 PHP 知識,請前往 Laravel / PHP 知識社區post