Download the PHP package sodaho/php-router without Composer

On this page you can find all versions of the php package sodaho/php-router. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package php-router

sodaho/php-router

PSR-7/PSR-15 router: routes, groups, middleware, named routes, JSON response helpers and a response emitter.

Requirements

Installation

Quick start

Reference

Router (Sodaho\Router\Router, implements Contract\RouterInterface)

Signature Description
__construct(array $config = []) / static create(array $config = []): self Configuration.
static fromEnv(array $config = []): self Adds the variables of Configuration.
static boot(array $config, string $routesFile): void create(), loadRoutes(), run().
loadRoutes(string $file): self File returning function (RouteCollector $r) {…}.
setContainer(ContainerInterface $container): self PSR-11 container for classes by name.
setDebug(bool $debug): self / isDebug(): bool Debug mode, see Security.
setBasePath(string $basePath): self Prefix of routes and addresses: /api, /api/, api alike.
setBaseUrl(?string $baseUrl): self Base URL of absoluteUrl(); null, '', '0': none.
middleware(string\|array\|object $middleware): self Middleware for every request, first = outermost.
app(string $prefix, string $directory, array $options = []): self Web app folder, see AppFolder.
setErrorHandler(callable $handler): self / on(string $event, callable $callback): static See below / Hooks.
match(ServerRequestInterface $request): RouteMatch Looks the request up, runs nothing.
handle(ServerRequestInterface $request): ResponseInterface PSR-15; does not throw.
url(string $name, array $params = []): string / absoluteUrl(…) See UrlGenerator.
run(): void Request from PHP's globals, handle(), send.
emit(ResponseInterface $response, bool $withBody = true): void See run() and emit().
__clone() Throws RouterException after the first use.

RouteCollector ($r in the routes file)

Signature Description
get(string $pattern, mixed $handler): Route Also post() put() patch() delete() options() head()
match(array $methods, string $pattern, mixed $handler): Route RFC 9110 tokens, upper-cased.
any(string $pattern, mixed $handler): Route GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.
redirect(string $from, string $to, int $status = 302): Route GET and HEAD, a RedirectHandler.
group(string $prefix, callable $callback): void Prefix for the routes in $callback.
middlewareGroup(string\|array\|object $middleware, callable $callback, array $attributes = []): void Middleware.
attributeGroup(array $attributes, callable $callback): void Inner wins per key, also in middlewareGroup().
addPattern(string $name, string $regex): self / addPatterns(array $patterns): self Type for {x:name}.
setPreserveTrailingSlash(bool $preserve): self true: mode strict (set by the router).
getRoutes(): array / getPatterns(): array Route objects; types as name => regex.
getData(): array [static routes, dynamic routes]; freezes the routes.

A handler is [Controller::class, 'method'] (the container's entry, else new when the constructor needs no argument), a callable ([$object, 'method'], a closure, an invokable object) or a RequestHandlerInterface. Controllers and callables get the request first and each placeholder as a named argument; a RequestHandlerInterface gets the request alone. A handler returns a ResponseInterface. A container entry that is no object of the named class (for middleware: no MiddlewareInterface) is a 500.

Type Regular expression Cast (failure: 400 INVALID_PARAMETER)
none: {id} [^/]+ string
int -?\d+ int; 01, -0 and overflow fail
float -?\d+(?:\.\d+)? float; overflow fails
bool true\|false\|0\|1, any case bool
alpha, alphanum, slug [a-zA-Z]+, [a-zA-Z0-9]+, [a-z0-9-]+ string
uuid, ulid 8-4-4-4-12 hex digits; 26 of [0-9A-Za-z] string
any (?:[^/]+(?:/[^/]+)*(?:/(?=\z))?)?: slashes, no empty segment string

Refused with RouterException where the route is written:

Matching: static routes (no placeholder) first, then dynamic routes in order of definition. A request path with %2F, %5C, a backslash, a control character or a ./.. segment (also encoded) is a 404 before the table is asked. A 500 (reported to error): a parameter named like an attribute the request carries; a route expression PCRE gives up on (backtrack limit, JIT stack); a placeholder named like the first parameter of a controller or callable.

Trailing slash mode strict (default): /users and /users/ are two routes; in group('/api'), get('') is /api and get('/') is /api/. Mode ignore: trailing slashes of routes and requests are dropped (/ stays).

Route

Built by the collector: __construct(array $methods, string $pattern, mixed $handler, array $middleware = [], ?string $name = null, array $attributes = []).

Signature Description
Readonly: array $methods, string $pattern, mixed $handler Set by the collector.
array $middleware, ?string $name, array $attributes Assignable until the table is built.
middleware(string\|array\|object $middleware): self Appends middleware.
name(string $name): self / attribute(string $key, mixed $value): self Name for url(); attribute.
getAttribute(string $key, mixed $default = null): mixed Reads an attribute.

RouteMatch

Signature Description
const FOUND, NOT_FOUND, METHOD_NOT_ALLOWED Values of $status.
Readonly: int $status, string $method, string $path $path: see below.
Readonly: ?Route $route, array $params, array $casts, bool $viaGet $params not cast; HEAD via GET.
isFound(): bool / allowedMethods(): array Status FOUND / methods of the path, HEAD behind GET.

$path is the path the table was asked with (decoded, no base path); where the table was not asked, the request path (decoded outside the base path, as sent for a path refused before the table). At METHOD_NOT_ALLOWED, $route is the path's GET route, else that of the first allowed method: its attributes are not those of the method asked for. handle() takes over a RouteMatch this router made for the same method and path; any other is looked up again.

Response (Sodaho\Router\Response, static)

Signature Status
success(mixed $data, ?string $message = null, ?array $meta = null) 200
created(mixed $data, ?string $message = null, ?string $location = null) 201, Location
accepted(mixed $data, ?string $message = null) / noContent() 202 / 204 without body
paginated(array $items, int $total, int $page, int $perPage) 200, meta.pagination
error(string $message, int $status = 400, ?string $code = null, ?array $details = null) $status
notFound(?string $resource = null, string\|int\|null $identifier = null) 404
unauthorized(?string $message = null) / forbidden(?string $message = null) 401 / 403
validationError(array $errors) / methodNotAllowed(array $allowedMethods) 422 / 405 with Allow
tooManyRequests(int $retryAfter) 429, Retry-After
serverError(?string $message = null, ?array $debug = null) 500
html(string $content, int $status = 200) / text(string $content, int $status = 200) HTML / text, UTF-8
json(mixed $data, int $status = 200, string $contentType = 'application/json') $data, no envelope
redirect(string $url, int $status = 302) REDIRECT_STATUSES: 301, 302, 303, 307, 308
setResponder(ResponderInterface $responder): void / reset(): void Set the responder / JsonResponder
getResponder(): ResponderInterface Current responder
Responder (Service\…; body: the array as JSON) Success Error (4xx/5xx)
JsonResponder {"success": true, "data", "message"?, "meta"?} {"success": false, "message", "error": {…}}
RfcResponder(string $typeBaseUri = 'about:blank') {"data", "message"?, "meta"?} RFC 9457 problem+json

error of JsonResponder holds message, code, details. RfcResponder: type from the code (NOT_FOUND → <base>/not-found; about:blank without code or with the base about:blank, the default), title from the message, status of the response, detail, instance and other keys from the details; type, title, status of the details are dropped.

ResponderInterface: formatSuccess(mixed $data, ?string $message = null, ?array $meta = null): array, formatError(string $message, ?string $code = null, ?array $details = null): array, getContentType(): string (4xx/5xx) and getSuccessContentType(): string (2xx/3xx).

UrlGenerator

Signature Description
__construct(array $routes = [], ?array $patterns = null) Routes; $patterns of getPatterns().
setBasePath(string $basePath): void Put in front of every address.
setBaseUrl(?string $baseUrl): void null, '': none; else the rule of baseUrl.
setIgnoreTrailingSlash(bool $ignore): void The router's mode ignore.
setEncodeParams(bool $encode): void Deprecated since 2.2.0; false throws.
url(string $name, array $params = []): string Relative address.
absoluteUrl(string $name, array $params = []): string Base URL and url().
hasRoute(string $name): bool Whether a route has the name.

AppFolder

Signature Description
__construct(string $prefix, string $directory, array $options = []) Built by app(); options below.
readonly string $prefix, const TYPES/HASHED No trailing slash ('': root); ext => type; bundler regex.
owns(string $path): bool Whether the path lies under the prefix.
serve(ServerRequestInterface $request, string $path): ?ResponseInterface The file, the start page or null.

RedirectHandler (Middleware\RedirectHandler)

Signature Description
__construct(string $target, int $status = 302) Target with {name} placeholders.
handle(ServerRequestInterface $request): ResponseInterface Fills them from _route_params.
getTarget(): string / getStatus(): int Target and status as given.

Other classes

run() and emit()

Status, headers and (with withBody) the body size are read before the first byte. Header lines go out first, the status line last. Fields that exist once per message (Content-Type, Content-Length, Location, ETag, …) replace what the host set; others (Vary, Cache-Control, Set-Cookie, …) are added. The body is read in emitChunkSize chunks.

Refused When run() emit()
Body closed or detached; a getter throws before sending 500 throws
Status outside 100–599 before sending 500 throws
Reason phrase or header value with a control character other than a tab before sending 500 throws
Protocol version not \d or \d.\d; header name not an RFC 9110 token before sending 500 throws
Transfer-Encoding; Content-Length not one value of at most 18 significant digits before sending 500 throws
Content-Length on 1xx or 204; one other than 0 on 205 before sending 500 throws
withBody true: a body of size other than 0 (or unknown) on 1xx, 204, 205, 304 before sending 500 throws
withBody true, a status with content: Content-Length above 0, body size 0 before sending 500 throws
No byte for emitIdleTimeout s; body shorter or longer than Content-Length after headers reported throws

Configuration

Key Variable Default Allowed Refused
debug APP_DEBUG false bool, bool-like ('true', '0', 'on', 'no'), falsy other truthy values
basePath ROUTER_BASE_PATH '' plain path; null, false other types; %XX, \, ?, #, ., ..
baseUrl APP_URL null http(s)://host[:port][/path] other forms (user info, \, query, blank)
trailingSlash ROUTER_TRAILING_SLASH 'strict' 'strict', 'ignore'; null, '' other values
urlEncoding ROUTER_URL_ENCODING true values that mean on off; other truthy values
routesFile — null string other types
implicitHead — true as debug as debug
emitChunkSize — 8192 int or digit string, 1024 to 16777216 other values
emitIdleTimeout — 30 seconds above 0 to 3600; string with 6 decimals at most other values
app() option Default Allowed Refused
index 'index.html' a file name /, \, :, leading dot, control char, trailing dot or space
types TYPES, null ext => type, null removes not array; ext not [a-z0-9]+; bad type; PHP sources
immutable null regex on the path below the prefix, e.g. AppFolder::HASHED no valid regex
cacheIndex 'no-cache' Cache-Control of the start page; null: none empty, control char
cacheImmutable 'public, max-age=31536000, immutable' for paths immutable matches as cacheIndex
cacheOther 'no-cache' for every other file as cacheIndex

RouterException for an unknown option, a missing folder, a prefix in use, and a prefix that is no plain path (a segment with a leading dot, a separator or control character, a trailing dot or space).

Hooks

Event When Payload
dispatch The handler of a route returned method, path, route, handler, params, duration
notFound The router answers 404 method, path
methodNotAllowed 405 method, path, allowed_methods
error An exception the router answers or reports exception, method, path, status (last key)
error run()/emit() found output started type ('emit'), message, exception, status
hookError A hook threw event, exception

Exceptions

Class When Members
RouterException What the router refuses, see above getDebugMessage(): ?string
DuplicateRouteException Method and pattern taken; one name on two patterns
RouteNotFoundException url(), absoluteUrl() with an unknown name debug message lists the route names
NotFoundException For applications; the router answers 404 itself
MethodNotAllowedException For applications; the router answers 405 itself getAllowedMethods(): array

Security

Testing

composer test (PHPUnit; suites test:unit, test:integration, test:feature, test:security), composer analyse (PHPStan: src level max, tests level 8), composer cs (dry run), composer validate --strict. No environment variables; tests start PHP_BINARY -S 127.0.0.1:<free port> and PHP_BINARY -r.

Upgrading

See CHANGELOG.md.

License

MIT

Parts of this project (refactoring, documentation, code review) were developed with AI assistance (Claude).


All versions of php-router with dependencies

PHP Build Version
Package Version
Requires php Version ^8.5
psr/http-message Version ^2.0
psr/http-server-handler Version ^1.0
psr/http-server-middleware Version ^1.0
psr/container Version ^2.0
psr/http-factory Version ^1.1
nyholm/psr7 Version ^1.8.2
nyholm/psr7-server Version ^1.1
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package sodaho/php-router contains the following files

Loading the files please wait ...