Download the PHP package pmjones/auto-route without Composer

On this page you can find all versions of the php package pmjones/auto-route. 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 auto-route

AutoRoute

AutoRoute automatically maps incoming HTTP requests (by verb and path) to PHP action classes in a specified namespace, reflecting on a specified action method within that class to determine the dynamic URL argument values. Those parameters may be typical scalar values (int, float, string, bool), or arrays, or even value objects of your own creation. AutoRoute also helps you generate URL paths based on action class names, and checks the dynamic argument typehints for you automatically.

Install AutoRoute using Composer:

AutoRoute is low-maintenance. Merely adding a class to your source code, in the recognized namespace and with the recognized action method name, automatically makes it available as a route. No more managing a routes file to keep it in sync with your action classes!

AutoRoute is fast. In fact, it is roughly 2x faster than FastRoute in common cases -- even when FastRoute is using cached route definitions.

Note:

When comparing alternatives, please consider AutoRoute as being in the same category as AltoRouter, FastRoute, Klein, etc., and not of Aura, Laminas, Laravel, Symfony, etc.

Contents

Motivation

Regular-expression (regex) routers generally duplicate important information that can be found by reflection instead. If you change the action method parameters targeted by a route, you need to change the route regex itself as well. As such, regex router usage may be considered a violation of the DRY principle. For systems with only a few routes, maintaining a routes file as duplicated information is not such a chore. But for systems with a hundred or more routes, keeping the routes in sync with their target action classes and methods can be onerous.

Similarly, annotation-based routers place routing instructions in comments, often duplicating dynamic parameters that are already present in explicit method signatures.

As an alternative to regex and annotation-based routers, this router implementation eliminates the need for route definitions by automatically mapping the HTTP action class hierarchy to the HTTP method verb and URL path, reflecting on typehinted action method parameters to determine the dynamic portions of the URL. It presumes that the action class names conform to a well-defined convention, and that the action method parameters indicate the dynamic portions of the URL. This makes the implementation both flexible and relatively maintenance-free.

Examples

Given a base namespace of Project\Http and a base url of /, this request ...

GET /photos

... auto-routes to the class Project\Http\Photos\GetPhotos.

Likewise, this request ...

POST /photo

... auto-routes to the class Project\Http\Photo\PostPhoto.

Given an action class with method parameters, such as this ...

... the following request will route to it ...

GET /photo/1

... recognizing that 1 should be the value of $photoId.

AutoRoute supports static "tail" parameters on the URL. If the URL ends in a path segment that matches the tail portion of a class name, and the action class method has the same number and type of parameters as its parent or grandparent class, it will route to that class name. For example, given an action class with method parameters such as this ...

... the following request will route to it:

GET /photo/1/edit

Finally, a request for the root URL ...

GET /

... auto-routes to the class Project\Http\Get.

Tip:

Any HEAD request will auto-route to an explicit Project\Http\...\Head* class, if one exists. If an explicit Head class does not exist, the request will implicitly be auto-routed to the matching Project\Http\...\Get* class, if one exists.

How It Works

Class File Naming

Action class files are presumed to be named according to PSR-4 standards; further:

  1. The class name starts with the HTTP verb it responds to;

  2. Followed by the concatenated names of preceding subnamespaces;

  3. Ending in .php.

Thus, given a base namespace of Project\Http, the class Project\Http\Photo\PostPhoto will be the action for POST /photo[/*].

Likewise, Project\Http\Photos\GetPhotos will be the action class for GET /photos[/*].

And Project\Http\Photo\Edit\GetPhotoEdit will be the action class for GET /photo[/*]/edit.

An explicit Project\Http\Photos\HeadPhotos will be the action class for HEAD /photos[/*]. If the HeadPhotos class does not exist, the action class is inferred to be Project\Http\Photos\HeadPhotos instead.

Finally, at the URL root path, Project\Http\Get will be the action class for GET /.

Dynamic Parameters

The action method parameter typehints are honored by the Router. For example, the following action ...

... will respond to the following:

GET /photos/archive
GET /photos/archive/1970
GET /photos/archive/1970/08

... but not to the following ...

GET /photos/archive/z
GET /photos/archive/1970/z

... because z is not recognized as an integer. (More finely-tuned validations of the method parameters must be accomplished in the action method itself, or more preferably in the domain logic, and cannot be intuited by the Router.)

The Router can recognize typehints of int, float, string, bool, and array.

For bool, the Router will case-insensitively cast these URL segment values to true: 1, t, true, y, yes. Similarly, it will case-insensitively cast these URL segment values to false: 0, f, false, n, no.

For array, the Router will use str_getcsv() on the URL segment value to generate an array. E.g., an array typehint for a segment value of a,b,c will receive ['a', 'b', 'c'].

Finally, trailing variadic parameters are also honored by the Router. Given an action method like the following ...

... the Router will honor this request ...

GET /photos/by-tag/foo/bar/baz/

... and recognize the method parameters as __invoke('foo', 'bar', 'baz').

Extended Example

By way of an extended example, these classes would be routed to by these URLs:

HEAD Requests

RFC 2616 requires that "methods GET and HEAD must be supported by all general-purpose servers".

As such, AutoRoute will automatically fall back to a Get* action class if a relevant Head* action class is not found. This keeps you from having to create a Head* class for every possible Get* action.

However, you may still define any Head* action class you like, and AutoRoute will use it.

Usage

Instantiate the AutoRoute container class with the top-level HTTP action namespace and the directory path to classes in that namespace:

You may use named constructor parameters if you wish:

Then pull the Router out of the container, and call route() with the HTTP request method verb and the path string to get back a Route:

You can then dispatch to the action class method using the returned Route information, or handle errors:

Debugging

To see how the Router gets where it does, examine the Route $messages property:

In addition, you may inject a custom PSR-3 LoggerInterface implementation factory as part of custom configuration.

Generating Route Paths

Using the AutoRoute container, pull out the Generator:

Then call the generate() method with the action class name, along with any action method parameters as variadic arguments:

Tip:

Using the action class name for the route name means that all routes in AutoRoute are automatically named routes.

The Generator will automatically check the argument values against the action method signature to make sure the values will be recognized by the Router. This means that you cannot (or at least, should not!) be able to generate a path that the Router will not recognize.

Custom Configuration

You may set these named constructor parameters at AutoRoute instantiation time to configure its behavior.

baseUrl

You may specify a base URL (i.e., a URL path prefix) using the following named constructor parameter:

The Router will ignore the base URL when determining the target action class for the route, and the Generator will prefix all paths with the base URL.

ignore

Some UI systems may use a shared Request object, in which case it is easy to inject the Request into the action constructor. However, other systems may not have access to a shared Request object, or may be using a Request that is fully-formed only at the moment the Action is called, so it must be passed in some way other than via the constructor.

Typically, these kinds of parameters are passed at the moment the action is called, which means they must be part of the action method signature. However, AutoRoute will see that parameter and incorrectly interpret it as a dynamic segment; for example:

To remedy this, AutoRoute can skip over any number of leading parameters on the action method. To do so, set the number of parameters to ignore using the following named constructor parameter:

... and then any new Router and Generator will ignore the first parameter.

Note that you will need to pass that first parameter yourself when you invoke the action:

loggerFactory

To inject a custom PSR-3 Logger instance into the Router, use the following named constructor parameter:

method

If you use an action method name other than __invoke(), such as exec() or run(), you can tell AutoRoute to reflect on its parameters instead using the following named constructor parameter:

The Router and Generator will now examine the exec() method to determine the dynamic segments of the URL path.

suffix

If your code base gives all action class names the same suffix, such as "Action", you can tell AutoRoute to disregard that suffix using the following named constructor parameter:

The Router and Generator will now ignore the suffix portion of the class name.

wordSeparator

By default, the Router and Generator will inflect static URL path segments from foo-bar to FooBar, using the dash as a word separator. If you want to use a different word separator, such as an underscore, you may do using the following named constructor parameter:

This will cause the Router and Generator to inflect from foo_bar to FooBar (and back again).

Dumping All Routes

You can dump a list of all recognized routes, and their target action classes, using the bin/autoroute-dump.php command line tool. Pass the base HTTP action namespace, and the directory where the action classes are stored:

The output will look something like this:

You can specify alternative configurations with these command line options:

Creating Classes From Routes

AutoRoute provides minimalist support for creating class files based on a route verb and path, using a template.

To do so, invoke autoroute-create.php with the base namespace, the directory for that namespace, the HTTP verb, and the URL path with parameter token placeholders.

For example, the following command ...

... will create this class file at ./src/Http/Photo/GetPhoto.php:

The command will not overwrite existing files.

You can specify alternative configurations with these command line options:

The default class template file is resources/templates/action.tpl. If you decide to write a custom template of your own, the available string-replacement placeholders are:

These names should be self-explanatory.

Note:

Even with a custom template, you will almost certainly need to edit the new file to add a constructor, typehints, default values, and so on. The file creation functionality is necessarily minimalist, and cannot account for all possible variability in your specific situation.

Questions and Recipes

Child Resources

N.b.: Deeply-nested child resources are currently considered a poor practice, but they are common enough that they demand attention here.

Deeply-nested child resources are supported, but their action class method parameters must conform to a "routine" signature, so that the Router and Generator can recognize which segments of the URL are dynamic and which are static.

  1. A child resource action MUST have at least the same number and type of parameters as its "parent" resource action; OR, in the case of static tail parameter actions, exactly the same number and type or parameters as its "grandparent" resource action. (If there is no parent or grandparent resource action, then it need not have any parameters.)

  2. A child resource action MAY add parameters after that, either as required or optional.

  3. When the URL path includes any of the optional parameter segments, routing to further child resource actions beneath it will be terminated.

Tip:

The above terms "parent" and "grandparent" are used in the URL path sense, not in the class hierarchy sense.

Fine-Grained Input Validation

Q: How do I specify something similar to the regex route path('/foo/{id}')->token(['id' => '\d{4}']) ?

A: You don't. (However, see the topic on "Value Objects as Action Parameters", below.)

Your domain does fine validation of the inputs, not your routing system (coarse validation only). AutoRoute, in casting the params to arguments, will set the type on the argument, which may raise an InvalidArgument or NotFound exception if the value cannot be typecast correctly.

For example, in the action:

Then, in the domain:

Value Objects as Action Parameters

Q: Can I use an object (instead of a scalar or array) as an action parameter?

A: Yes, with some caveats.

Although you cannot specify input validation in the routing itself, per se, you can specify a value object as parameter, and do validation within its constructor. These value objects may come from anywhere, including the Domain.

For example, your underlying Application Service classes might need Domain value objects as inputs, with the action creating those value objects itself:

The corresponding value object might look like this:

To avoid the manual conversion of dynamic path segments to value objects, you may use the value object type itself as an action parameter, like so:

Given the HTTP request GET /company/1, the Router will notice that the action parameter is of the CompanyId type, and use the relevant segments of the URL path to build the CompanyId argument.

Further, you can attempt to validate and/or sanitize the value object arguments, throwing an exception on invalidation. For example:

It is up to you to examine Route::$error for these exceptions and send the appropriate HTTP response.

Some additional notes:

Generating Paths With Value Objects

When generating a path for an action that uses value objects, you need to pass the individual arguments as they would appear in the URL, not as they appear when calling the action. Given the above GetCompany action, you would not instantiate CompanyId; instead, you would pass the integer value argument.

Dumping Paths With Value Objects

When you dump the routes via the Dumper, you will find that the dynamic segments associated with value objects are named for the value object constructor parameters. If you have multiple value objects in an action method signature, and those value objects use the same parameter names in their constructors, you will see repetition of those names in the dumped path. This does not cause any ill effect to AutoRoute itself, though it might be confusing when reviewing the path strings.

Capturing Other Request Values

Q: How to capture the hostname? Headers? Query parameters? Body?

A: Read them from your Request object.

For example, in the action:

Then, in the domain:


All versions of auto-route with dependencies

PHP Build Version
Package Version
Requires php Version ^8.0
psr/log Version ^3.0
pmjones/throwable-properties Version ^1.0
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 pmjones/auto-route contains the following files

Loading the files please wait ....