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

Geocoder Bundle Laravel Package

avtonom/geocoder-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require avtonom/geocoder-bundle ~1.1
    

    Ensure your composer.json has PHP ≥5.3.2 and Symfony 2.3/3.x.

  2. Register the Bundle Add to app/AppKernel.php (Symfony 2.x) or config/bundles.php (Symfony 3.x+):

    new Avtonom\GeocoderBundle\AvtonomGeocoderBundle(),
    new YamilovS\SypexGeoBundle\YamilovsSypexGeoBundle(),
    new Bazinga\Bundle\GeocoderBundle\BazingaGeocoderBundle(),
    
  3. Configure the Bundle Define the database path in config/packages/yamilovs_sypex_geo.yaml (Symfony 3.x+) or app/config/config.yml:

    yamilovs_sypex_geo:
        database_path: "%kernel.project_dir%/var/SypexGeoDatabase/SxGeoCity.dat"
    
  4. Update the Geo Database Run the console command to fetch the latest database:

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

    Alternative: Manually download/unzip from SypexGeo.

  5. First Use Case: Geocoding an IP Inject the geocoder service and use the sypex_geo provider:

    use Bazinga\Bundle\GeocoderBundle\Geocoder\GeocoderManagerInterface;
    
    class MyService {
        public function __construct(private GeocoderManagerInterface $geocoder) {}
    
        public function getLocation(string $ip): ?array {
            $result = $this->geocoder->geocodeQuery('sypex_geo', $ip);
            return $result->first()?->getCoordinates();
        }
    }
    

Implementation Patterns

Core Workflows

  1. Geocoding IP Addresses Use the sypex_geo provider for fast, offline IP-to-location lookups:

    $geocoder = $this->geocoder->getProvider('sypex_geo');
    $result = $geocoder->geocode('192.0.2.1');
    $city = $result->first()?->getCity();
    
  2. Chaining Providers Combine sypex_geo with other providers (e.g., Google Maps) for fallback logic:

    # config/packages/bazinga_geocoder.yaml
    bazinga_geocoder:
        providers:
            chain:
                providers: [avtonom_geocoder.geocoder.sypex_geo, google_maps]
    
  3. Reverse Geocoding Convert coordinates to human-readable addresses:

    $reverse = $geocoder->reverse('51.5074', '-0.1278');
    $address = $reverse->first()?->getStreet();
    

Integration Tips

  • Symfony Forms: Use the GeocoderType for address fields:
    use Bazinga\Bundle\GeocoderBundle\Form\Type\GeocoderType;
    
    $builder->add('address', GeocoderType::class, [
        'provider' => 'sypex_geo',
        'error_bubbling' => true,
    ]);
    
  • Event Listeners: Trigger actions on geocoding events (e.g., log failed lookups):
    use Bazinga\Bundle\GeocoderBundle\Event\GeocodeEvent;
    
    public function onGeocodeFailure(GeocodeEvent $event) {
        if ($event->getProviderName() === 'sypex_geo') {
            $this->logger->error('SypexGeo failed for IP: '.$event->getQuery());
        }
    }
    
  • Caching: Cache results to reduce database hits:
    $cache = $this->container->get('cache.app');
    $key = 'geo_'.$ip;
    if (!$cache->has($key)) {
        $result = $geocoder->geocode($ip);
        $cache->set($key, $result, 3600); // Cache for 1 hour
    }
    

Gotchas and Tips

Pitfalls

  1. Database Path Issues

    • Ensure the SxGeoCity.dat path is absolute and writable.
    • Common fix: Use %kernel.project_dir% (Symfony 2.x) or %kernel.project_dir% (Symfony 3.x+) in config.
    • Debug: Check if the file exists via:
      php bin/console debug:config yamilovs_sypex_geo
      
  2. Outdated Database

    • The bundled database (SxGeoCity.dat) may be stale. Always run:
      php bin/console yamilovs:sypex-geo:update-database-file
      
    • Manual Update: Replace the file in var/SypexGeoDatabase/ with the latest from SypexGeo.
  3. Provider Name Mismatch

    • The provider is registered as avtonom_geocoder.geocoder.sypex_geo (not sypex_geo directly).
    • Fix: Use the full service ID in chaining:
      providers:
          chain:
              providers: [avtonom_geocoder.geocoder.sypex_geo]
      
  4. IPv6 Limitations

    • SypexGeo primarily supports IPv4. For IPv6, consider falling back to an online provider (e.g., google_maps).
  5. Symfony 4/5 Compatibility

    • This bundle is Symfony 2/3-only. For Symfony 4/5, use geocoder-php/geocoder with the SxGeo adapter directly.

Debugging Tips

  • Check Geocoding Results:
    $result = $geocoder->geocode('192.0.2.1');
    dump($result->getMessage()); // Debug errors
    
  • Validate IP Format: SypexGeo expects raw IP strings (e.g., "192.0.2.1"), not objects or malformed strings.
  • Log Provider Output: Enable debug mode to inspect the underlying SxGeo object:
    $provider = $this->geocoder->getProvider('avtonom_geocoder.geocoder.sypex_geo');
    dump($provider->getHandler()->getGeo());
    

Extension Points

  1. Custom Database Paths Override the default path via environment variables:

    yamilovs_sypex_geo:
        database_path: "%env(SYPEX_GEO_PATH)%"
    

    Set in .env:

    SYPEX_GEO_PATH=/custom/path/SxGeoCity.dat
    
  2. Extending Geocoder Results Add custom methods to the result object by subclassing Geocoder\Result\Result:

    class ExtendedResult extends \Geocoder\Result\Result {
        public function getCountryCode(): ?string {
            return $this->getData()['country_code'] ?? null;
        }
    }
    

    Bind it in services.yaml:

    services:
        App\Geocoder\ExtendedResult:
            tags: ['bazinga.geocoder.result']
    
  3. Bulk Geocoding Process multiple IPs efficiently:

    $ips = ['192.0.2.1', '198.51.100.2'];
    $results = $geocoder->geocodeBatch($ips);
    foreach ($results as $ip => $result) {
        $this->logger->info(sprintf('IP %s -> %s', $ip, $result->first()?->getCity()));
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky