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

Uri Components Laravel Package

league/uri-components

Immutable value objects for URI components (host, path, query, etc.) from The PHP League. PHP 8.1+. Supports IDN hosts (intl or polyfill) and IPv4 conversion (GMP/BCMath/64-bit). Built atop league/uri, uri-interfaces, and PSR-7.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Immutable Value Objects: The package provides immutable URI components (e.g., Scheme, Host, Query, Path), aligning well with Laravel’s emphasis on immutability and functional programming patterns. This reduces unintended side effects in request/response handling, API routing, and URL generation.
  • PSR-7 Compatibility: Leverages PSR-7 (UriInterface, StreamInterface) for interoperability with Laravel’s HTTP layer (e.g., Illuminate\Http\Request, Illuminate\Http\Response). Enables seamless integration with middleware, message buses, or HTTP clients.
  • Domain-Specific Logic: Advanced methods like Domain::isSubdomainOf(), Query::getList(), or Modifier::redactPathSegments() offer granular control for:
    • API Gateway Routing: Dynamic subdomain-based routing (e.g., api.example.com vs. admin.example.com).
    • URL Sanitization: Redacting sensitive path segments (e.g., /user/{id}/user/[REDACTED]).
    • Query Parameter Manipulation: Batch operations on query strings (e.g., withList(), appendList()) for pagination, filtering, or analytics.
  • WHATWG/URL Standard Support: Compatibility with modern URL parsing (e.g., WhatWg\Url) ensures consistency with browser behavior, critical for SPAs or hybrid Laravel/JS apps.

Integration Feasibility

  • Laravel Ecosystem Synergy:
    • Routing: Replace manual string concatenation in Route::get() with immutable Uri objects for dynamic routes (e.g., Route::get($uri->withPath('/dynamic')->toString())).
    • HTTP Clients: Use Modifier to construct URLs for Guzzle/HttpClient requests with fluent syntax (e.g., $uri->withQuery(['page' => 2])->toString()).
    • Validation: Integrate with Laravel’s Validator to enforce URI component rules (e.g., Host::isValid(), Scheme::isHttp()).
  • Existing Laravel Packages:
    • Laravel HTTP Client: Extend Http facade to accept UriComponent objects for requests.
    • Laravel Scout: Customize search URLs with Query::appendList() for faceted search.
    • Laravel Echo/Pusher: Generate WebSocket URIs with Scheme::isWebsocket() checks.
  • Database/ORM: Store/Retrieve URI components as JSON (e.g., Query objects) in json columns for audit logs or dynamic redirects.

Technical Risk

  • PHP Version Dependency:
    • Risk: Requires PHP ≥8.1 (Laravel 9+ supports this, but legacy apps may not).
    • Mitigation: Use symfony/polyfill-intl-idn and gmp/bcmath polyfills for older PHP versions.
  • Learning Curve:
    • Risk: Immutable objects and fluent methods may require refactoring existing URL-handling code.
    • Mitigation: Start with Modifier for incremental adoption (e.g., replace str_replace in URLs with Modifier::redactPathSegments()).
  • Performance Overhead:
    • Risk: Immutable objects may increase memory usage for high-throughput APIs.
    • Mitigation: Benchmark critical paths (e.g., URL generation in loops) and cache Uri instances where possible.
  • Breaking Changes:
    • Risk: Active development (7.x releases) may introduce API changes.
    • Mitigation: Pin to a stable minor version (e.g., ^7.8) and monitor changelogs.

Key Questions

  1. Use Case Prioritization:
    • Which Laravel features will benefit most from URI components? (e.g., routing, HTTP clients, validation).
    • Example: "Will we use Domain::isSubdomainOf() for multi-tenant routing?"
  2. Migration Strategy:
    • Should we replace all string-based URLs in the codebase immediately, or adopt incrementally?
    • Example: "Start with Modifier for API URLs, then extend to routing."
  3. Testing Impact:
    • How will existing URL-related tests (e.g., feature tests with hardcoded paths) adapt?
    • Example: "Can we mock UriComponent objects in unit tests?"
  4. Team Adoption:
    • Does the team have experience with immutable objects or functional programming?
    • Example: "Provide code samples for Query::withList() vs. manual array manipulation."
  5. Performance Trade-offs:
    • Are there bottlenecks where immutable objects could degrade performance?
    • Example: "Benchmark URL generation in a high-traffic endpoint."

Integration Approach

Stack Fit

  • Laravel Core:
    • Routing: Replace Route::get('/user/{id}', ...) with dynamic Uri objects for complex paths (e.g., /user/{id}/posts/{post_id}).
      $uri = Uri::create('/user')->withPathSegment('123')->withPath('/posts')->withPathSegment('456');
      Route::get($uri->toString(), ...);
      
    • Request Handling: Parse incoming URIs into components for validation or transformation:
      $request->getUri()->getQuery()->getList('filter'); // Get all 'filter' values
      
    • Response Generation: Construct redirects or API responses with immutable components:
      return redirect()->to($uri->withQuery(['utm_source' => 'laravel'])->toString());
      
  • HTTP Layer:
    • Guzzle/HttpClient: Build requests from components:
      $client->get($uri->withScheme('https')->withHost('api.example.com')->toString());
      
    • Middleware: Modify URIs in middleware (e.g., add auth tokens to query strings):
      $uri->getQuery()->withPair('auth_token', $token);
      
  • Validation:
    • Use component methods in Laravel’s Validator:
      Validator::make($request->all(), [
          'url' => ['required', function ($attribute, $value, $fail) {
              if (!Uri::tryFrom($value)?->getHost()?->isValid()) {
                  $fail('Invalid URL.');
              }
          }],
      ]);
      
  • Database:
    • Store URI components as JSON for dynamic redirects or audit logs:
      $uri->getQuery()->jsonSerialize(); // Store in DB
      

Migration Path

  1. Phase 1: Adopt Modifier for URL Construction
    • Replace manual string concatenation with Modifier in:
      • API URL generation.
      • Redirects.
      • HTTP client requests.
    • Example:
      // Before
      $url = "https://api.example.com/users?page={$page}";
      
      // After
      $url = Uri::create('https://api.example.com/users')->withQuery(['page' => $page])->toString();
      
  2. Phase 2: Integrate with Routing
    • Use Uri objects in Route::get() for dynamic paths.
    • Example:
      $baseUri = Uri::create('/user')->withHost(config('app.url'));
      Route::get($baseUri->withPathSegment('{id}')->toString(), [UserController::class, 'show']);
      
  3. Phase 3: Leverage Components in Validation/Middleware
    • Extract Host, Query, or Path components for business logic.
    • Example:
      // Middleware to check subdomains
      $request->getUri()->getHost()->getDomain()->isSubdomainOf('admin.example.com');
      
  4. Phase 4: Optimize for Performance
    • Cache frequently used Uri instances (e.g., API base URLs).
    • Benchmark and profile critical paths.

Compatibility

  • Laravel Versions:
    • Compatible: Laravel 9+ (PHP 8.1+). For Laravel 8, use PHP 8.1 with polyfills.
    • Legacy: Requires significant refactoring for Laravel <8 (PHP <8.1).
  • Dependencies:
    • Conflicts: None major. league/uri-components is independent of Laravel’s URI handling.
    • Polyfills: Add to composer.json if needed:
      "require": {
          "symfony/polyfill-intl-idn": "^1.27",
          "ext-gmp": "*" // or ext-bcmath
      }
      
  • PSR-7 Compliance:
    • Works alongside Laravel’s Psr\Http\Message implementations (e.g., Symfony\Component\HttpFoundation\Request).

Sequencing

  1. Prerequisites:
    • Upgrade to PHP 8.1+ and Laravel 9+ (if not already).
    • Install the package:
      composer require league/uri-components
      
  2. Initial Integration:
    • Start with Modifier in a single service (e.g., ApiClient).
    • Example
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
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