Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Api Symfony Bundle Laravel Package

2gis/api-symfony-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require 2gis/api-symfony-bundle:dev-master
    

    Add to AppKernel.php:

    new DGis\Bundle\ApiBundle\DGisApiBundle(),
    
  2. 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%
    
  3. 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]);
        }
    }
    

Implementation Patterns

Common Workflows

  1. Search Requests:

    $client->search('query', [
        'lat' => 55.7558,
        'lon' => 37.6173,
        'category' => 'cafe',
    ]);
    
  2. Place Details:

    $client->place('place_id');
    
  3. Geocoding:

    $client->geocode('address');
    
  4. Reverse Geocoding:

    $client->reverseGeocode('lat', 'lon');
    

Integration Tips

  • 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
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Management:

    • Hardcoding keys in parameters.yml is insecure for production. Use environment variables or a secrets manager.
    • Validate the key is set in config.yml; the bundle does not enforce this.
  2. Rate Limiting:

    • The 2GIS API has strict rate limits (e.g., 1 request per second for free tier). Ignoring this will result in blocked requests.
    • Fix: Implement exponential backoff or use a queue system (e.g., Symfony Messenger) for bulk operations.
  3. Error Handling:

    • The bundle wraps the underlying 2gis/api-client, but custom exceptions may not be thrown for all error cases (e.g., invalid responses, network issues).
    • Fix: Always wrap API calls in 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)
      }
      
  4. Deprecation:

    • The package is unmaintained (0 stars, no dependents). Assume breaking changes in future Symfony versions (e.g., Flex recipes, new DI components).
    • Fix: Fork the repository or create a wrapper service layer to isolate changes.
  5. Locale/Region Support:

    • The API may return region-specific results (e.g., "Moscow" vs. "Moskva"). Test thoroughly if your app serves multiple regions.
    • Fix: Pass region or country parameters explicitly:
      $client->search('Moscow', ['country' => 'ru']);
      

Debugging Tips

  1. 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.

  2. Validate Requests: Use the 2GIS API Playground to test endpoints manually before integrating.

  3. Common Issues:

    • 403 Forbidden: Invalid or revoked API key. Regenerate the key in the 2GIS Partner Portal.
    • 429 Too Many Requests: Hit rate limits. Implement retries with delays.
    • 500 Internal Server Error: API-side issue. Check the 2GIS Status Page or contact support.

Extension Points

  1. 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'
    
  2. 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 }
    
  3. 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
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle