2gis/api-client
PHP-клиент для API 2ГИС: регионы, справочник/каталог, транспорт и геоданные. Установка через Composer, простой вызов методов API 2.0 и работа с ответами сервиса. Лицензия MIT.
dev-master as no stable release exists):
composer require 2gis/api-client:dev-master
AppServiceProvider:
public function register()
{
$this->app->singleton('2gis.client', function ($app) {
return new \TwoGis\Client(config('services.2gis.key'));
});
}
config/services.php:
'2gis' => [
'key' => env('TWOGIS_API_KEY'),
'timeout' => 30,
],
$regions = app('2gis.client')->regions()->getAll();
// Search for businesses in a region (e.g., Moscow)
$search = app('2gis.client')->catalog()->search([
'region' => 'moscow',
'category' => 'restaurants',
'limit' => 10,
]);
Service Provider Pattern Bind the client to Laravel’s container for dependency injection:
// app/Providers/2gisServiceProvider.php
public function register()
{
$this->app->bind('2gis', function ($app) {
return new \TwoGis\Client($app['config']['services.2gis.key']);
});
}
Facade for Clean Access Create a facade to simplify usage:
// app/Facades/2gis.php
public static function regions()
{
return app('2gis')->regions();
}
Usage:
$regions = \Facade\2gis::regions()->getAll();
Repository Pattern Encapsulate API calls in repositories:
// app/Repositories/2gis/RegionRepository.php
public function findById($id)
{
return app('2gis')->regions()->getById($id);
}
Queue-Based API Calls Offload heavy requests to queues (e.g., bulk geodata fetches):
// Dispatch a job
dispatch(new FetchRegionsJob());
// Job implementation
public function handle()
{
$regions = app('2gis')->regions()->getAll();
// Process regions...
}
throttle middleware or spatie/rate-limiter:
Route::middleware(['throttle:100,1'])->group(function () {
Route::get('/search', [SearchController::class, 'index']);
});
Illuminate\Support\Facades\Cache:
$regions = Cache::remember('2gis.regions', now()->addHours(1), function () {
return app('2gis')->regions()->getAll();
});
try {
$data = app('2gis')->catalog()->search($params);
} catch (\TwoGis\Exception\ApiException $e) {
Log::error("2GIS API Error: " . $e->getMessage());
return response()->json(['error' => 'Service unavailable'], 503);
}
Eloquent Models Attach geodata to models:
// app/Models/Business.php
public function getCoordinatesAttribute()
{
$geo = app('2gis')->geo()->getById($this->geo_id);
return [$geo['lon'], $geo['lat']];
}
Scout Driver Create a custom Scout driver for 2GIS geospatial search:
// app/Search/2gisEngine.php
public function search($query)
{
return app('2gis')->catalog()->search([
'q' => $query,
'limit' => 100,
]);
}
API Resources Format responses with Laravel’s API Resources:
// app/Http/Resources/RegionResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'full_name' => $this->full_name,
];
}
Deprecated PHP Features
curl_init(), json_decode() without associative flag, or other deprecated functions.rector to upgrade:
composer require rector/rector --dev
vendor/bin/rector process src --dry-run
No Type Safety
Illuminate\Support\Facades\Validator:
$validator = Validator::make($response, [
'id' => 'required|integer',
'name' => 'required|string',
]);
Hardcoded Endpoints
api.2gis.com). Override via config:
// config/2gis.php
'endpoints' => [
'regions' => env('TWOGIS_REGIONS_ENDPOINT', 'https://api.2gis.com/2.0/regions'),
],
No Retry Logic
$client = new \TwoGis\Client($apiKey, [
'http_client' => Http::withOptions([
'timeout' => 30,
'connect_timeout' => 10,
'retry' => true,
]),
]);
Alpha-Stage APIs
Enable API Logging Add a logger to the client:
$client = new \TwoGis\Client($apiKey, [
'logger' => function () {
return new \Monolog\Logger('2gis');
},
]);
Inspect Raw Responses
Use dd() or Log::debug() to inspect raw API responses:
$response = app('2gis')->regions()->getAll();
Log::debug('Raw 2GIS response:', $response);
Mock the Client for Testing Use Laravel’s mocking to test without hitting the API:
$this->mock(\TwoGis\Client::class)->shouldReceive('regions')
->andReturnSelf()
->shouldReceive('getAll')
->andReturn([/* mock data */]);
Custom HTTP Client
Replace the default HTTP client (likely curl) with Guzzle:
$client = new \TwoGis\Client($apiKey, [
'http_client' => new \GuzzleHttp\Client(),
]);
Add New API Endpoints Extend the client class to support unsupported APIs:
// app/Extensions/2gis/ClientExtension.php
public function customEndpoint($params)
{
return $this->request('GET', '/custom', $params);
}
Webhook Support If 2GIS offers webhooks, create a Laravel event listener:
// app/Listeners/Handle2gisWebhook.php
public function handle($event)
{
$data = $event->data;
// Process webhook data...
}
API Key Format
Ensure your API key matches the expected format (e.g., Bearer token vs. plain key). Check 2GIS docs.
Region Codes
2GIS uses internal region codes (e.g., moscow vs. 1). Validate against their region list.
Pagination The package may not handle pagination. Implement manually:
$offset = 0;
$limit = 100;
do {
$results = app('2gis')->catalog()->search([
'offset' => $offset,
'limit' => $limit,
]);
// Process $results
$offset += $limit;
} while (!empty($results));
$ids = [1,
How can I help you explore Laravel packages today?