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

Sypex Geo Bundle Laravel Package

alexeyfedotof/sypex-geo-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require alexeyfedotof/sypex-geo-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        AlexeyFedotof\SypexGeoBundle\SypexGeoBundle::class => ['all' => true],
    ];
    
  2. Configure the Bundle Edit config/packages/sypex_geo.yaml (auto-generated):

    sypex_geo:
        api_key: 'your_api_key_here'  # Required for cloud API mode
        cache_dir: '%kernel.cache_dir%/sypex_geo'  # Cache directory
        mode: 'file'  # 'file' (local DB) or 'cloud' (API)
        database_path: '%kernel.project_dir%/var/sypex_geo.db'  # Only for 'file' mode
    
  3. First Use Case: Fetch Geo Data Inject the service in a controller or command:

    use AlexeyFedotof\SypexGeoBundle\Service\SypexGeoService;
    
    public function __construct(private SypexGeoService $geoService) {}
    
    public function getGeoData(Request $request): array
    {
        $ip = $request->getClientIp();
        $data = $this->geoService->getGeoData($ip);
        return $data; // e.g., ['country' => 'US', 'city' => 'New York']
    }
    

Implementation Patterns

Common Workflows

  1. Local Database Mode (Offline)

    • Download the latest database via CLI:
      php bin/console sypex-geo:update-database
      
    • Use cached results for performance (default: 24h TTL).
    • Ideal for internal tools or air-gapped environments.
  2. Cloud API Mode (Real-Time)

    • Configure mode: 'cloud' and provide an API key.
    • Useful for high-precision needs (e.g., fraud detection).
    • Example:
      $this->geoService->getGeoData($ip, ['use_cache' => false]); // Bypass cache
      
  3. Event-Driven Geo Enrichment

    • Subscribe to sypex_geo.data_fetched event to extend data:
      // src/EventListener/SypexGeoListener.php
      public function onGeoDataFetched(GeoDataEvent $event) {
          $event->setData(['custom_field' => 'value']);
      }
      
    • Register in services.yaml:
      services:
          App\EventListener\SypexGeoListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'sypex_geo.data_fetched' }
      
  4. Bulk IP Lookup

    • Process arrays of IPs efficiently:
      $ips = ['1.2.3.4', '5.6.7.8'];
      $results = $this->geoService->getGeoDataBatch($ips);
      

Integration Tips

  • Symfony Cache: Leverage Symfony’s cache system for TTL management:
    # config/packages/cache.yaml
    frameworks:
        cache:
            app: cache.adapter.redis
    
  • API Rate Limiting: For cloud mode, implement a decorator to handle API limits:
    $this->geoService->setRateLimiter(new CustomRateLimiter());
    
  • Testing: Mock the service in tests:
    $this->geoService = $this->createMock(SypexGeoService::class);
    $this->geoService->method('getGeoData')->willReturn(['country' => 'Test']);
    

Gotchas and Tips

Pitfalls

  1. Database Updates

    • Local DB files expire (typically every 3 months). Forgetting to update (sypex-geo:update-database) leads to stale data.
    • Fix: Schedule a cron job or use a Symfony command listener.
  2. API Key Leaks

    • Hardcoding api_key in config/packages/sypex_geo.yaml exposes it in Git.
    • Fix: Use Symfony’s %env(resolve:...)% or env():
      api_key: '%env(SYPEX_GEO_API_KEY)%'
      
  3. Cache Invalidation

    • The bundle doesn’t auto-invalidate cache on DB updates. Manual clearing may be needed:
      php bin/console cache:clear
      
  4. IPv6 Support

    • The underlying library (yamilovs/sypex-geo) has limited IPv6 support. Test thoroughly if your audience uses IPv6.
  5. Cloud Mode Latency

    • API calls add ~100-300ms latency. Avoid in performance-critical paths (e.g., high-traffic APIs).

Debugging

  • Enable Verbose Logging Add to config/packages/sypex_geo.yaml:

    debug: true
    

    Logs appear in var/log/dev.log.

  • Validate IP Input The service silently returns null for invalid IPs. Add validation:

    if (!filter_var($ip, FILTER_VALIDATE_IP)) {
        throw new \InvalidArgumentException('Invalid IP address');
    }
    

Extension Points

  1. Custom Data Fields Extend the GeoData class to add fields:

    // src/Entity/CustomGeoData.php
    class CustomGeoData extends GeoData {
        public function getCustomField() { ... }
    }
    

    Override the service to return your class:

    services:
        App\Service\CustomSypexGeoService:
            decorates: 'alexeyfedotof.sypex_geo.service'
            arguments: ['@alexeyfedotof.sypex_geo.service']
    
  2. Database Path Overrides Dynamically set the DB path based on environment:

    $this->geoService->setDatabasePath(
        $this->getParameter('kernel.project_dir') . '/var/sypex_geo_prod.db'
    );
    
  3. Fallback Logic Implement a fallback for API/cloud failures:

    try {
        return $this->geoService->getGeoData($ip);
    } catch (\RuntimeException $e) {
        return $this->fallbackGeoService->getData($ip);
    }
    

Performance Tips

  • Batch Processing: For bulk operations, use getGeoDataBatch() instead of looping.
  • Cache Tags: Assign cache tags to related entities to invalidate on DB updates:
    $cache->set('geo_data_' . $ip, $data, ['sypex_geo_db'], 86400);
    
  • Async Updates: Offload DB updates to a queue (e.g., Symfony Messenger) to avoid blocking requests.
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime