VOOZH about

URL: https://deepwiki.com/hypervel/router/3.1-urlgenerator-class

⇱ UrlGenerator Class | hypervel/router | DeepWiki


Loading...
Menu

UrlGenerator Class

The UrlGenerator class is the core component responsible for generating URLs within Hypervel Router applications. It provides methods for creating URLs to named routes, application paths, and assets, while managing URL schemes (HTTP/HTTPS) and origins. The class implements the Hypervel\Router\Contracts\UrlGenerator interface and integrates with Hyperf's dependency injection container, request context, and configuration system.

For information about creating and validating signed URLs, see Signed URLs and Security. For global helper functions that provide convenient access to URL generation, see URL Helper Functions.

Sources: src/UrlGenerator.php1-519 src/Contracts/UrlGenerator.php1-152

Class Architecture and Dependencies

The UrlGenerator class is instantiated through Hyperf's dependency injection container and relies on several framework components to function correctly.

Core Dependencies

DependencyPurpose
ContainerInterfaceResolves framework services and configuration
DispatcherFactoryAccesses named route definitions
RequestInterfaceRetrieves current request information
ConfigInterfaceReads application configuration (app URL, signing key)
SessionInterfaceTracks previous URL (optional)

Class Structure


Sources: src/UrlGenerator.php28-61 src/Contracts/UrlGenerator.php14-151

Instance Properties

The class maintains several internal properties for caching and configuration:

PropertyTypePurpose
$formatHostUsing?ClosureOptional callback for custom host formatting
$formatPathUsing?ClosureOptional callback for custom path formatting
$signedKey?stringCustom key for signing URLs (overrides config)
$cachedScheme?stringCached URL scheme to avoid repeated lookups
$forceScheme?stringForced scheme for all generated URLs

Sources: src/UrlGenerator.php33-57

Named Route URL Generation

The route() method generates URLs for named routes by looking up route definitions from the DispatcherFactory and substituting route parameters.

Method Signature


URL Generation Flow


Parameter Substitution

The method uses array_reduce() to iterate through route segments, replacing parameter placeholders with values from the $parameters array. Any remaining parameters are appended as a query string.

Example Route Pattern Processing:

  • Route pattern: /user/{id}/posts/{post}
  • Parameters: ['id' => 123, 'post' => 456, 'filter' => 'recent']
  • Result: /user/123/posts/456?filter=recent

Sources: src/UrlGenerator.php64-100

Exception Handling

The method throws InvalidArgumentException if the named route does not exist:

Sources: src/UrlGenerator.php72-74

General URL Generation

The UrlGenerator provides several methods for creating URLs to application paths, with support for secure protocols and query parameters.

Method Overview

MethodPurposeReturn Type
to(string $path, array $extra = [], ?bool $secure = null)Generate URL to any pathstring
query(string $path, array $query = [], array $extra = [], ?bool $secure = null)Generate URL with query parametersstring
secure(string $path, array $extra = [])Generate HTTPS URLstring

The to() Method

The to() method is the primary URL generation method. It handles both absolute and relative paths, validates existing URLs, and appends extra path segments.


Key Features:

  1. URL Validation: Returns the path unchanged if it's already a valid URL (includes scheme, mailto, tel, etc.)
  2. Parameter Formatting: Converts UrlRoutable objects to their route keys
  3. Path Encoding: URL-encodes extra path segments
  4. Query String Preservation: Extracts and preserves existing query strings

Sources: src/UrlGenerator.php102-120 src/UrlGenerator.php454-463

The query() Method

The query() method builds upon to() by merging additional query parameters with any existing query string in the path.

Implementation Details:

  1. Extracts existing query string from path using extractQueryString()
  2. Parses existing query parameters into an array
  3. Merges provided query array with existing parameters
  4. Calls to() with the merged query string

Sources: src/UrlGenerator.php122-134

The secure() Method

A convenience method that forces HTTPS scheme by calling to() with $secure = true.

Sources: src/UrlGenerator.php136-142

Asset URL Generation

Asset URLs are used for static resources like images, CSS, and JavaScript files. The UrlGenerator provides specialized methods for generating these URLs.

Asset Methods

MethodPurpose
asset(string $path, ?bool $secure = null)Generate URL to application asset
secureAsset(string $path)Generate HTTPS URL to asset
assetFrom(string $root, string $path, ?bool $secure = null)Generate asset URL from custom domain (e.g., CDN)

Asset URL Structure


Key Difference from to():

  • Asset URLs do not apply format() method or custom formatters
  • Path segments are not URL-encoded
  • Extra parameters are not supported
  • Direct concatenation of root and path

Sources: src/UrlGenerator.php144-174

Current Request URLs

The UrlGenerator provides methods to retrieve information about the current and previous requests.

Request Context Methods

MethodReturns
full()Complete URL including query string
current()URL without query string
previous(bool|string $fallback = false)URL of previous request
previousPath($fallback = false)Path portion of previous URL

URL Retrieval Flow


Request Context Availability

The UrlGenerator gracefully handles cases where no request context exists (e.g., CLI commands):

  1. With Request Context: Uses RequestInterface from container to retrieve URI
  2. Without Request Context: Falls back to app.url from configuration

Sources: src/UrlGenerator.php299-353 src/UrlGenerator.php511-518

URL Scheme Management

The UrlGenerator provides fine-grained control over URL schemes (HTTP/HTTPS) through multiple configuration mechanisms.

Scheme Configuration Methods

MethodPurposeScope
formatScheme(?bool $secure = null)Determine scheme for current operationPer-call
forceScheme(?string $scheme)Force specific scheme for all URLsGlobal
forceHttps(bool $force = true)Force HTTPS for all URLsGlobal

Scheme Resolution Priority


Implementation Details

Caching Behavior:

  • The $cachedScheme property stores the resolved scheme to avoid repeated lookups
  • Cache is cleared when forceScheme() is called

Forced Scheme:

  • Setting forceScheme('https') applies globally to all URL generation
  • Pass null to clear the forced scheme

Sources: src/UrlGenerator.php176-190 src/UrlGenerator.php387-405

URL Origin Management

The useOrigin() method allows overriding the base URL for all generated URLs, useful for multi-domain applications or testing scenarios.

Origin Configuration


Behavior:

  • Stores the origin in Hyperf Context as __url.forced_root for request isolation
  • Clears cached root URI to force recalculation
  • Pass null to remove forced origin and revert to automatic detection

Root URL Resolution


Context Keys:

  • __url.forced_root: Stores forced origin when useOrigin() is called
  • __request.root.uri: Caches the automatically detected root URI

Sources: src/UrlGenerator.php408-422 src/UrlGenerator.php487-509

URL Formatting and Customization

The UrlGenerator supports custom formatting logic for both the host and path portions of generated URLs.

Formatter Methods

MethodCallback SignatureApplied To
formatHostUsing(Closure $callback)fn(string $host): stringHost portion of URL
formatPathUsing(Closure $callback)fn(string $path): stringPath portion of URL

Format Method

The format() method is the central point where formatters are applied:


Usage Example:


Sources: src/UrlGenerator.php356-371 src/UrlGenerator.php424-442

Utility Methods

The UrlGenerator includes several utility methods used internally and available for external use.

URL Validation

isValidUrl(string $path): bool

Determines if a given string is already a complete, valid URL. Returns true if the path:

  • Starts with common URL schemes: #, //, mailto:, tel:, sms:, http://, https://
  • Passes PHP's filter_var($path, FILTER_VALIDATE_URL) check

Sources: src/UrlGenerator.php373-385

Query String Extraction

extractQueryString(string $path): array

Splits a path into the base path and query string components.

Returns: [basePathWithoutQuery, queryStringWithQuestionMark]

Example:

  • Input: /users?page=2&sort=name
  • Output: ['/users', '?page=2&sort=name']

Sources: src/UrlGenerator.php465-475

Parameter Formatting

formatParameters(array $parameters): array

Processes route parameters by converting UrlRoutable objects to their route key values using getRouteKey().

Sources: src/UrlGenerator.php454-463

Signed Key Retrieval

getSignedKey(): string

Returns the key used for signing URLs. Priority:

  1. Custom key set via setSignedKey()
  2. Application key from app.key configuration

Sources: src/UrlGenerator.php477-485

Integration with Dependency Injection

The UrlGenerator is registered in Hyperf's container through the ConfigProvider class and can be resolved via dependency injection or the container directly.

Container Registration

The class is bound to its contract interface:


Resolution Methods


Common Usage Patterns:

  1. Constructor Injection:

    
    
  2. Container Resolution:

    
    
  3. Helper Functions: (See page 3.3 for details)

    
    

Sources: src/UrlGenerator.php59-61

Method Reference Summary

URL Generation Methods

MethodPrimary Use CaseAbsoluteSecure Option
route()Named routesConfigurableVia scheme
to()Application pathsYesConfigurable
query()URLs with query paramsYesConfigurable
secure()Force HTTPSYesAlways HTTPS
asset()Static assetsYesConfigurable
secureAsset()Static assets (HTTPS)YesAlways HTTPS
assetFrom()CDN/custom domainYesConfigurable

Signature Methods

MethodPurposeSee Also
signedRoute()Create signed URLPage 3.2
temporarySignedRoute()Create expiring signed URLPage 3.2
hasValidSignature()Validate signed requestPage 3.2
hasValidRelativeSignature()Validate relative signed URLPage 3.2
hasCorrectSignature()Check signature correctnessPage 3.2
signatureHasNotExpired()Check expirationPage 3.2

Configuration Methods

MethodEffect DurationStored In
forceScheme()Request lifecycleInstance property
forceHttps()Request lifecycleInstance property
useOrigin()Current request (coroutine)Hyperf Context
formatHostUsing()Request lifecycleInstance property
formatPathUsing()Request lifecycleInstance property
setSignedKey()Request lifecycleInstance property

Sources: src/Contracts/UrlGenerator.php14-151 src/UrlGenerator.php28-519

Refresh this wiki

On this page