Spatie URL
A small PHP library to parse, build, and manipulate URLs with an immutable, fluent API.
Repository Health
Technical Analysis
Spatie URL is a lightweight PHP package for working with URLs. It lets you parse a URL string into its parts, read any component (scheme, host, path, query, segments), and build or transform URLs through a fluent, immutable API.
The Url class is immutable — every with* method returns a new instance — which keeps URL manipulation predictable. It implements PSR-7’s UriInterface, so it drops into PSR-7 aware code, and includes a query-parameter bag for reading and modifying query strings.
What You Get
- An immutable
Urlvalue object with getters for every URL component - Fluent
withScheme/withHost/withPath/withQueryParametertransformers that return new instances - A query-parameter bag for reading, adding, and removing query-string values
- PSR-7
UriInterfacecompatibility and path-segment access helpers
Common Use Cases
- Parsing an incoming URL and reading or validating individual parts
- Building or rewriting URLs (changing host, path, or query) safely without string concatenation
- Manipulating query-string parameters in a structured way
Under The Hood
Architecture — The heart is Url.php, an immutable value object implementing PSR-7’s UriInterface; each with* method clones and mutates a copy. QueryParameterBag encapsulates query-string state, Scheme/SchemeValidator/BaseValidator (behind a Contracts\Validator) handle scheme validation, and Exceptions\InvalidArgument signals bad input. The class mixes in spatie/macroable so consumers can extend it with custom methods.
Tech Stack — PHP 8.0+ with only two runtime dependencies: psr/http-message (for UriInterface) and spatie/macroable. No framework coupling.
Code Quality — Small and clean, with a comprehensive test suite covering parsing, building, immutability, matching, schemes, segments, and query parameters as separate test files. Immutability is explicitly tested, which guards the core contract.
API Design — The API reads naturally: Url::fromString(...) plus getters and with* transformers mirror PSR-7 while staying friendlier, and the query-parameter bag removes the usual pain of query-string handling. Immutability makes behavior predictable with minimal surprises.