Installation:
composer require 2gis/api-symfony-bundle:dev-master
Add to AppKernel.php:
new DGis\Bundle\ApiBundle\DGisApiBundle(),
Configuration:
Define API key in app/parameters.yml:
parameters:
dgis_key: "your_api_key_here"
Configure bundle in app/config.yml:
d_gis_api:
key: %dgis_key%
First Use Case: Inject the API client in a service/controller:
use DGis\Bundle\ApiBundle\Client\ClientInterface;
class MyController extends Controller
{
public function __construct(ClientInterface $client)
{
$this->client = $client;
}
public function searchAction()
{
$response = $this->client->search('Москва');
return $this->render('template.html.twig', ['results' => $response]);
}
}
Search Requests:
$client->search('query', [
'lat' => 55.7558,
'lon' => 37.6173,
'category' => 'cafe',
]);
Place Details:
$client->place('place_id');
Geocoding:
$client->geocode('address');
Reverse Geocoding:
$client->reverseGeocode('lat', 'lon');
Dependency Injection:
Always inject ClientInterface to ensure testability and flexibility.
public function __construct(ClientInterface $client) { ... }
Response Handling: Wrap API calls in services for better error handling and logging:
public function getPlaceDetails($id)
{
try {
return $this->client->place($id);
} catch (\Exception $e) {
$this->logger->error('2GIS API Error: ' . $e->getMessage());
throw new \RuntimeException('Failed to fetch place details');
}
}
Caching Responses: Use Symfony’s cache system to reduce API calls:
$cache = $this->get('cache.app');
$cacheKey = '2gis_place_' . $id;
if (!$cache->has($cacheKey)) {
$data = $this->client->place($id);
$cache->set($cacheKey, $data, 3600); // Cache for 1 hour
} else {
$data = $cache->get($cacheKey);
}
Batch Processing: For bulk operations (e.g., fetching multiple places), use a loop with rate-limiting:
foreach ($placeIds as $id) {
$this->client->place($id);
sleep(1); // Respect API rate limits
}
API Key Management:
parameters.yml is insecure for production. Use environment variables or a secrets manager.config.yml; the bundle does not enforce this.Rate Limiting:
Error Handling:
2gis/api-client, but custom exceptions may not be thrown for all error cases (e.g., invalid responses, network issues).try-catch blocks and log errors:
try {
$response = $this->client->search('query');
} catch (\DGis\Client\Exception\ApiException $e) {
$this->logger->error('2GIS API Error: ' . $e->getMessage());
// Handle gracefully (e.g., return cached data or fallback UI)
}
Deprecation:
Locale/Region Support:
region or country parameters explicitly:
$client->search('Moscow', ['country' => 'ru']);
Enable API Debugging: Configure the underlying client to log raw requests/responses:
# app/config.yml
d_gis_api:
key: %dgis_key%
debug: true # If supported; check the underlying `2gis/api-client` docs
Alternatively, use a proxy like Charles to inspect traffic.
Validate Requests: Use the 2GIS API Playground to test endpoints manually before integrating.
Common Issues:
Custom Clients:
Extend the bundle’s ClientInterface to add domain-specific methods:
class CustomClient implements ClientInterface
{
private $client;
public function __construct(ClientInterface $client)
{
$this->client = $client;
}
public function searchNearbyPois($lat, $lon, $radius = 1000)
{
return $this->client->search('', [
'lat' => $lat,
'lon' => $lon,
'radius' => $radius,
'category' => 'poi',
]);
}
}
Register as a service:
services:
app.custom_2gis_client:
class: App\Service\CustomClient
arguments:
- '@d_gis_api.client'
Event Listeners: Subscribe to API events (if the underlying client supports them) to log or transform responses:
// src/AppBundle/EventListener/ApiListener.php
class ApiListener
{
public function onApiResponse(GetResponseEvent $event)
{
$response = $event->getResponse();
// Modify or log $response
}
}
Bind in services.yml:
services:
app.api_listener:
class: App\EventListener\ApiListener
tags:
- { name: kernel.event_listener, event: dgis.api.response, method: onApiResponse }
Configuration Overrides:
Override bundle defaults in config.yml:
d_gis_api:
key: %dgis_key%
timeout: 30 # Override default timeout
base_uri: https://api.2gis.com/ru # Specify region
How can I help you explore Laravel packages today?