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

yamilovs/sypex-geo-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation Run composer require yamilovs/sypex-geo-bundle:^2.0 in your project root. Ensure your composer.json includes the package under require.

  2. Enable the Bundle Add new Yamilovs\Bundle\SypexGeoBundle\SypexGeoBundle() to your AppKernel.php (or config/bundles.php for Symfony Flex).

  3. Basic Configuration Configure the bundle in config/packages/yamilovs_sypex_geo.yaml:

    yamilovs_sypex_geo:
        mode: FILE
        database_path: "%kernel.project_dir%/var/SypexGeoDatabase/SxGeoCity.dat"
    

    Create the var/SypexGeoDatabase directory manually if it doesn’t exist.

  4. Download the Database Run the console command to fetch the latest database:

    php bin/console yamilovs:sypex-geo:update-database-file
    

    Alternatively, manually download SxGeoCity.dat from SypexGeo’s official site and place it in the configured path.

  5. First Query Use the service in a controller or service:

    use Yamilovs\Bundle\SypexGeoBundle\Service\SypexGeoService;
    
    class GeoController extends AbstractController
    {
        public function getGeoInfo(SypexGeoService $geoService)
        {
            $ip = '8.8.8.8'; // Example IP
            $geoData = $geoService->getGeo($ip);
            return $this->json($geoData);
        }
    }
    

Implementation Patterns

Core Workflows

  1. IP Geolocation Lookup The primary use case is fetching geolocation data for an IP address. Inject SypexGeoService and call:

    $geoData = $geoService->getGeo($ipAddress);
    

    Returns an array with keys like country, region, city, latitude, longitude, etc.

  2. Batch Processing Configure mode: BATCH in config.yaml to process multiple IPs efficiently:

    yamilovs_sypex_geo:
        mode: BATCH
        database_path: "..."
    

    Use the batch method:

    $ips = ['8.8.8.8', '1.1.1.1'];
    $batchResults = $geoService->getGeoBatch($ips);
    
  3. Memory Mode (For Testing) Set mode: MEMORY to load the database into memory (faster but consumes more RAM):

    yamilovs_sypex_geo:
        mode: MEMORY
    

    Ideal for testing or environments with low IP query volume.

  4. Proxy Configuration If behind a proxy (e.g., corporate network), configure it in config.yaml:

    yamilovs_sypex_geo:
        connection:
            proxy:
                host: 'proxy.example.com'
                port: 8080
                auth:
                    user: 'proxy_user'
                    password: 'proxy_pass'
    

Integration Tips

  1. Symfony Events Trigger geolocation logic on user login or request events. Example:

    // src/EventListener/GeoListener.php
    public function onKernelRequest(GetResponseEvent $event)
    {
        $ip = $event->getRequest()->getClientIp();
        $geoData = $this->geoService->getGeo($ip);
        $event->getRequest()->attributes->set('geo_data', $geoData);
    }
    
  2. Caching Layer Cache results to reduce database lookups. Use Symfony’s cache system:

    $cacheKey = 'geo_' . md5($ip);
    $geoData = $this->cache->get($cacheKey);
    if (!$geoData) {
        $geoData = $this->geoService->getGeo($ip);
        $this->cache->set($cacheKey, $geoData, 3600); // Cache for 1 hour
    }
    
  3. Database Updates Schedule regular updates via cron or Symfony’s scheduler:

    # Run daily at 2 AM
    0 2 * * * cd /path/to/project && php bin/console yamilovs:sypex-geo:update-database-file
    
  4. Custom Geo Data Handling Extend the service to transform raw data into domain-specific objects:

    class GeoDataTransformer
    {
        public function transform(array $rawData): GeoData
        {
            return new GeoData(
                $rawData['country'],
                $rawData['city'] ?? null,
                $rawData['latitude'] ?? 0,
                $rawData['longitude'] ?? 0
            );
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Database Path Permissions Ensure the database_path directory is writable by the web server user (e.g., www-data or apache). Run:

    chmod -R 755 var/SypexGeoDatabase
    
  2. Outdated Database The database file (SxGeoCity.dat) expires every 3 months. Set up automated updates or monitor for stale data. Check the SypexGeo update frequency for details.

  3. Memory Mode Limitations MEMORY mode loads the entire database into RAM, which can cause high memory usage for large databases. Avoid in production unless necessary.

  4. Proxy Authentication If using a proxy with authentication, ensure the credentials are securely stored (e.g., in environment variables or Symfony’s parameter_bag).

  5. IPv6 Support The bundle primarily supports IPv4. For IPv6, validate input IPs or use a fallback mechanism:

    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        // Handle IPv6 or return a default response
    }
    

Debugging

  1. Console Command Errors If update-database-file fails, check:

    • Internet connectivity (if downloading automatically).
    • Proxy settings in config.yaml.
    • File permissions for the database_path.
  2. Geo Data Not Found Verify the IP address is valid and the database file is not corrupted. Test with a known IP (e.g., 8.8.8.8 for Google DNS).

  3. Performance Issues

    • High latency? Ensure the database file is up-to-date and the mode is optimized (e.g., FILE for high throughput).
    • Slow batch processing? Reduce batch size or switch to MEMORY mode (if RAM allows).
  4. Logging Enable debug mode to log geo lookups:

    yamilovs_sypex_geo:
        debug: true
    

    Check logs in var/log/dev.log for errors or warnings.


Extension Points

  1. Custom Database Paths Override the default path per environment using Symfony’s parameter system:

    # config/packages/dev/yamilovs_sypex_geo.yaml
    yamilovs_sypex_geo:
        database_path: "%kernel.project_dir%/var/dev/SypexGeoDatabase/SxGeoCity.dat"
    
  2. Extending Geo Data Create a custom service to enrich or validate geo data:

    class EnhancedGeoService
    {
        public function __construct(private SypexGeoService $geoService)
        {
        }
    
        public function getEnhancedGeo(string $ip): array
        {
            $geoData = $this->geoService->getGeo($ip);
            $geoData['is_eu'] = $this->isEuCountry($geoData['country']);
            return $geoData;
        }
    
        private function isEuCountry(string $countryCode): bool
        {
            // Implement EU country logic
        }
    }
    
  3. Database Validation Add a command to validate the database file integrity:

    php bin/console debug:container | grep sypex_geo
    

    Check if the service is properly initialized and the database path is correct.

  4. Alternative Data Sources Combine with other geo services (e.g., MaxMind) for fallback or redundancy:

    class FallbackGeoService
    {
        public function getGeo(string $ip): array
        {
            try {
                return $this->sypexGeoService->getGeo($ip);
            } catch (Exception $e) {
                return $this->maxMindService->getGeo($ip);
            }
        }
    }
    
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