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

Common Http Laravel Package

geocoder-php/common-http

Common HTTP layer for Geocoder PHP providers. Includes shared HTTP client abstractions, request/response handling, and helpers to integrate PSR-18 clients and PSR-7 messages, keeping geocoding providers lightweight and consistent across transports.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • HTTP Abstraction Layer: The package provides a clean abstraction for HTTP-based geocoding requests, aligning well with Laravel’s dependency injection and PSR standards. It decouples HTTP logic from geocoding providers, enabling modularity and easier provider swaps (e.g., switching between Google Maps, OpenStreetMap, or custom APIs).
  • PSR Compliance: Adherence to PSR-17 (HTTP Factories) and PSR-18 (HTTP Clients) ensures compatibility with Laravel’s ecosystem (e.g., Illuminate\Http\Client, Guzzle, or Symfony HTTP Client). This reduces vendor lock-in and simplifies future migrations.
  • Geocoder Integration: Designed as a dependency for the broader php-geocoder package, it fits seamlessly into Laravel applications requiring geospatial features (e.g., location-based services, distance calculations, or IP geolocation).
  • Laravel-Specific Synergies:
    • Service Container: The package’s constructor-based dependency injection aligns with Laravel’s IoC container, enabling easy binding of HTTP clients (e.g., HttpClient facade or custom PSR-18 clients).
    • Caching: Can integrate with Laravel’s cache layer (e.g., Cache::remember) to store geocoding responses, reducing API calls.
    • Queue Jobs: HTTP requests can be offloaded to Laravel Queues for async processing (e.g., geocoding user addresses during signup).

Integration Feasibility

  • Low Friction: The package is dependency-free (beyond PSR standards) and requires minimal boilerplate. Example integration:
    use Geocoder\Provider\OpenStreetMapProvider;
    use Geocoder\HttpAdapter\CommonHttpAdapter;
    use Psr\Http\Client\ClientInterface;
    use Psr\Http\Message\RequestFactoryInterface;
    
    $httpClient = new \GuzzleHttp\Client(); // or Laravel's HttpClient
    $requestFactory = new \Nyholm\Psr7\Factory\Psr17Factory();
    $adapter = new CommonHttpAdapter($httpClient, $requestFactory);
    
    $geocoder = new Geocoder\Geocoder();
    $geocoder->registerProvider('osm', new OpenStreetMapProvider($adapter));
    
  • Laravel Facades: Can wrap the package behind a custom facade (e.g., Geocoder::geocode('Paris')) for consistency with Laravel’s conventions.
  • Configuration: Supports environment-based configuration (e.g., .env for API keys) via Laravel’s config() helper.

Technical Risk

  • PSR-18 Dependency: Requires a PSR-18-compliant HTTP client (e.g., Guzzle, Symfony HTTP Client, or Laravel’s HttpClient). While Laravel’s HttpClient is PSR-18-compliant, custom implementations may need validation.
  • PHP Version: Drops PHP 7.x support (minimum PHP 8.0). High-risk for legacy Laravel apps (pre-8.x). Mitigation: Use Laravel’s PHP version constraints (e.g., ^8.0 in composer.json).
  • Breaking Changes: Refactoring in v4.x (e.g., removal of setMessageFactory) may require updates to custom providers. Test thoroughly if extending the package.
  • Rate Limiting/Retries: The package lacks built-in retry logic or circuit breakers. Laravel’s HttpClient supports retries, but custom providers may need additional handling.
  • Error Handling: Geocoding APIs often return non-200 responses (e.g., rate limits, invalid queries). The package delegates this to providers; ensure your app handles exceptions (e.g., Geocoder\Exception\UnsupportedProviderException).

Key Questions

  1. Provider Strategy:
    • Will you use multiple geocoding providers (e.g., fallback from OpenStreetMap to Google)? If so, how will you handle provider-specific configurations (e.g., API keys)?
    • Do you need custom providers? The package’s AbstractHttpProvider can be extended, but ensure compatibility with its refactored methods (e.g., getRequest()).
  2. Performance:
    • Will geocoding be sync or async? Async requires Laravel Queues + caching to avoid rate limits.
    • Do you need batch geocoding? The package doesn’t support bulk requests; consider chunking or a dedicated library.
  3. Cost:
    • Are you using paid APIs (e.g., Google Maps)? Budget for rate limits and caching to reduce costs.
  4. Fallback Mechanisms:
    • How will you handle failed requests (e.g., network issues, API downtime)? Implement retries or a backup provider.
  5. Testing:
    • Do you have mock HTTP clients for unit tests? Use Laravel’s HttpClient mocking or Mockery with PSR-18 interfaces.
  6. Monitoring:
    • Will you track geocoding success/failure rates? Log metrics via Laravel’s Log facade or a monitoring tool (e.g., Sentry).

Integration Approach

Stack Fit

  • Laravel Core: Fully compatible with Laravel’s HTTP stack (PSR-18 clients, HttpClient facade, Illuminate\Support\Facades\Http).
  • Ecosystem Synergies:
    • Caching: Integrate with Laravel’s cache (Cache::remember) to store responses (e.g., 1-hour TTL for static locations).
    • Queues: Offload geocoding to queues (e.g., GeocodeJob) for async processing.
    • Events: Dispatch events (e.g., Geocoded, GeocodeFailed) for observability.
    • Validation: Use Laravel’s validation (e.g., Rule::requiredIf) to sanitize input addresses.
  • Third-Party:
    • Guzzle/Symfony HTTP Client: Preferred PSR-18 clients for flexibility.
    • Laravel Scout: If using geocoding for full-text search, combine with Scout’s geospatial extensions.
    • Vite/PWA: For frontend maps (e.g., Leaflet/OpenLayers), geocode server-side and return coordinates to the client.

Migration Path

  1. Assess Current State:
    • Audit existing geocoding logic (e.g., direct API calls, custom scripts). Identify pain points (e.g., no retries, hardcoded keys).
  2. Phase 1: Core Integration (1–2 sprints):
    • Replace direct API calls with the geocoder-php stack.
    • Example:
      // Before: Direct Guzzle call
      $response = Http::get('https://api.openstreetmap.org/...');
      
      // After: Using geocoder-php
      $geocoder = app(Geocoder::class);
      $result = $geocoder->geocode('Paris');
      
    • Bind dependencies in AppServiceProvider:
      $this->app->bind(ClientInterface::class, function ($app) {
          return new \GuzzleHttp\Client();
      });
      
  3. Phase 2: Enhancements (1 sprint):
    • Add caching (e.g., Cache::remember).
    • Implement async geocoding with queues.
    • Set up monitoring/logging.
  4. Phase 3: Optimization (Ongoing):
    • A/B test providers (e.g., OpenStreetMap vs. custom API).
    • Optimize batch processing for bulk geocoding.

Compatibility

  • Laravel Versions:
    • LTS Support: Works with Laravel 9+ (PHP 8.0+). For Laravel 8.x, pin to PHP 8.0-compatible versions (e.g., geocoder-php/common-http:^4.4).
    • Legacy: Avoid if using Laravel <8.x (PHP 7.x unsupported).
  • PHP Extensions: No special extensions required beyond json, curl, or file_get_contents.
  • Database: No direct DB dependencies, but geocoded data (e.g., coordinates) may need storage in tables like:
    Schema::create('user_locations', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained();
        $table->string('address');
        $table->decimal('latitude', 10, 8);
        $table->decimal('longitude', 11, 8);
        $table->timestamps();
    });
    

### **Sequencing**
1. **Prerequisites**:
   - Upgrade to **PHP 8.0+** and Laravel 8+ if not already.
   - Install PSR-18 HTTP client (e.g., `guzzlehttp/guzzle` or `symfony/http-client`).
2. **Core Setup**:
   - Install packages:
     ```bash
     composer require geocoder-php/geocoder geocoder-php/common-http guzzlehttp/guzzle
     ```
   - Configure providers in `config/services.php`:
     ```
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.
craftcms/url-validator
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