Installation
Run composer require yamilovs/sypex-geo-bundle:^2.0 in your project root.
Ensure your composer.json includes the package under require.
Enable the Bundle
Add new Yamilovs\Bundle\SypexGeoBundle\SypexGeoBundle() to your AppKernel.php (or config/bundles.php for Symfony Flex).
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.
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.
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);
}
}
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.
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);
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.
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'
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);
}
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
}
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
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
);
}
}
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
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.
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.
Proxy Authentication
If using a proxy with authentication, ensure the credentials are securely stored (e.g., in environment variables or Symfony’s parameter_bag).
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
}
Console Command Errors
If update-database-file fails, check:
config.yaml.database_path.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).
Performance Issues
mode is optimized (e.g., FILE for high throughput).MEMORY mode (if RAM allows).Logging Enable debug mode to log geo lookups:
yamilovs_sypex_geo:
debug: true
Check logs in var/log/dev.log for errors or warnings.
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"
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
}
}
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.
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);
}
}
}
How can I help you explore Laravel packages today?