{"id":13450726,"url":"https://github.com/nikic/FastRoute","last_synced_at":"2025-03-23T16:32:04.359Z","repository":{"id":14190134,"uuid":"16896584","full_name":"nikic/FastRoute","owner":"nikic","description":"Fast request router for PHP","archived":false,"fork":false,"pushed_at":"2024-04-22T22:34:47.000Z","size":390,"stargazers_count":5159,"open_issues_count":24,"forks_count":451,"subscribers_count":180,"default_branch":"master","last_synced_at":"2025-03-18T16:12:20.209Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nikic.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-02-16T23:16:45.000Z","updated_at":"2025-03-15T20:58:57.000Z","dependencies_parsed_at":"2022-07-21T21:32:57.517Z","dependency_job_id":"39a2356d-9cd3-49d3-9572-e0ec6df3c6c9","html_url":"https://github.com/nikic/FastRoute","commit_stats":{"total_commits":146,"total_committers":50,"mean_commits":2.92,"dds":0.6986301369863014,"last_synced_commit":"34128a32009e1b41c4615bcd7d4c39968931e9ea"},"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nikic%2FFastRoute","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nikic%2FFastRoute/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nikic%2FFastRoute/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nikic%2FFastRoute/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nikic","download_url":"https://codeload.github.com/nikic/FastRoute/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245130938,"owners_count":20565746,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T07:00:37.680Z","updated_at":"2025-03-23T16:32:04.092Z","avatar_url":"https://github.com/nikic.png","language":"PHP","funding_links":[],"categories":["Uncategorized","Micro Frameworks","微型框架","PHP","路由 Routers","Table of Contents","\u003e 3k ★","目录","Route","路由( Routers )","类库","插件推荐","HTTP, APIs \u0026 Middleware"],"sub_categories":["Uncategorized","Routers","路由 Routers","路由","Globalization"],"readme":"FastRoute - Fast request router for PHP\n=======================================\n\n[![Build Status](https://img.shields.io/github/actions/workflow/status/nikic/FastRoute/phpunit.yml?branch=master\u0026style=flat-square)](https://github.com/nikic/FastRoute/actions?query=workflow%3A%22PHPUnit%20Tests%22+branch%3Amaster)\n\nThis library provides a fast implementation of a regular expression based router. [Blog post explaining how the\nimplementation works and why it is fast.][blog_post]\n\nInstall\n-------\n\nTo install with composer:\n\n```sh\ncomposer require nikic/fast-route\n```\n\nRequires PHP 8.1 or newer.\n\nUsage\n-----\n\nHere's a basic usage example:\n\n```php\n\u003c?php\n\nrequire '/path/to/vendor/autoload.php';\n\n$dispatcher = FastRoute\\simpleDispatcher(function(FastRoute\\ConfigureRoutes $r) {\n    $r-\u003eaddRoute('GET', '/users', 'get_all_users_handler');\n    // {id} must be a number (\\d+)\n    $r-\u003eaddRoute('GET', '/user/{id:\\d+}', 'get_user_handler');\n    // The /{title} suffix is optional\n    $r-\u003eaddRoute('GET', '/articles/{id:\\d+}[/{title}]', 'get_article_handler');\n});\n\n// Fetch method and URI from somewhere\n$httpMethod = $_SERVER['REQUEST_METHOD'];\n$uri = $_SERVER['REQUEST_URI'];\n\n// Strip query string (?foo=bar) and decode URI\nif (false !== $pos = strpos($uri, '?')) {\n    $uri = substr($uri, 0, $pos);\n}\n$uri = rawurldecode($uri);\n\n$routeInfo = $dispatcher-\u003edispatch($httpMethod, $uri);\nswitch ($routeInfo[0]) {\n    case FastRoute\\Dispatcher::NOT_FOUND:\n        // ... 404 Not Found\n        break;\n    case FastRoute\\Dispatcher::METHOD_NOT_ALLOWED:\n        $allowedMethods = $routeInfo[1];\n        // ... 405 Method Not Allowed\n        break;\n    case FastRoute\\Dispatcher::FOUND:\n        $handler = $routeInfo[1];\n        $vars = $routeInfo[2];\n        // ... call $handler with $vars\n        break;\n}\n```\n\n### Defining routes\n\nThe routes are defined by calling the `FastRoute\\simpleDispatcher()` function, which accepts\na callable taking a `FastRoute\\ConfigureRoutes` instance. The routes are added by calling\n`addRoute()` on the collector instance:\n\n```php\n$r-\u003eaddRoute($method, $routePattern, $handler);\n```\n\nThe `$method` is an uppercase HTTP method string for which a certain route should match. It\nis possible to specify multiple valid methods using an array:\n\n```php\n// These two calls\n$r-\u003eaddRoute('GET', '/test', 'handler');\n$r-\u003eaddRoute('POST', '/test', 'handler');\n// Are equivalent to this one call\n$r-\u003eaddRoute(['GET', 'POST'], '/test', 'handler');\n```\n\nBy default, the `$routePattern` uses a syntax where `{foo}` specifies a placeholder with name `foo`\nand matching the regex `[^/]+`. To adjust the pattern the placeholder matches, you can specify\na custom pattern by writing `{bar:[0-9]+}`. Some examples:\n\n```php\n// Matches /user/42, but not /user/xyz\n$r-\u003eaddRoute('GET', '/user/{id:\\d+}', 'handler');\n\n// Matches /user/foobar, but not /user/foo/bar\n$r-\u003eaddRoute('GET', '/user/{name}', 'handler');\n\n// Matches /user/foo/bar as well\n$r-\u003eaddRoute('GET', '/user/{name:.+}', 'handler');\n```\n\nCustom patterns for route placeholders cannot use capturing groups. For example `{lang:(en|de)}`\nis not a valid placeholder, because `()` is a capturing group. Instead you can use either\n`{lang:en|de}` or `{lang:(?:en|de)}`.\n\nFurthermore, parts of the route enclosed in `[...]` are considered optional, so that `/foo[bar]`\nwill match both `/foo` and `/foobar`. Optional parts are only supported in a trailing position,\nnot in the middle of a route.\n\n```php\n// This route\n$r-\u003eaddRoute('GET', '/user/{id:\\d+}[/{name}]', 'handler');\n// Is equivalent to these two routes\n$r-\u003eaddRoute('GET', '/user/{id:\\d+}', 'handler');\n$r-\u003eaddRoute('GET', '/user/{id:\\d+}/{name}', 'handler');\n\n// Multiple nested optional parts are possible as well\n$r-\u003eaddRoute('GET', '/user[/{id:\\d+}[/{name}]]', 'handler');\n\n// This route is NOT valid, because optional parts can only occur at the end\n$r-\u003eaddRoute('GET', '/user[/{id:\\d+}]/{name}', 'handler');\n```\n\nThe `$handler` parameter does not necessarily have to be a callback, it could also be a controller\nclass name or any other kind of data you wish to associate with the route. FastRoute only tells you\nwhich handler corresponds to your URI, how you interpret it is up to you.\n\n#### Shortcut methods for common request methods\n\nFor the `GET`, `POST`, `PUT`, `PATCH`, `DELETE` and `HEAD` request methods shortcut methods are available. For example:\n\n```php\n$r-\u003eget('/get-route', 'get_handler');\n$r-\u003epost('/post-route', 'post_handler');\n```\n\nIs equivalent to:\n\n```php\n$r-\u003eaddRoute('GET', '/get-route', 'get_handler');\n$r-\u003eaddRoute('POST', '/post-route', 'post_handler');\n```\n\n#### Route Groups\n\nAdditionally, you can specify routes inside a group. All routes defined inside a group will have a common prefix.\n\nFor example, defining your routes as:\n\n```php\n$r-\u003eaddGroup('/admin', function (FastRoute\\ConfigureRoutes $r) {\n    $r-\u003eaddRoute('GET', '/do-something', 'handler');\n    $r-\u003eaddRoute('GET', '/do-another-thing', 'handler');\n    $r-\u003eaddRoute('GET', '/do-something-else', 'handler');\n});\n```\n\nWill have the same result as:\n\n ```php\n$r-\u003eaddRoute('GET', '/admin/do-something', 'handler');\n$r-\u003eaddRoute('GET', '/admin/do-another-thing', 'handler');\n$r-\u003eaddRoute('GET', '/admin/do-something-else', 'handler');\n ```\n\nNested groups are also supported, in which case the prefixes of all the nested groups are combined.\n\n### Caching\n\nThe reason `simpleDispatcher` accepts a callback for defining the routes is to allow seamless\ncaching. By using `cachedDispatcher` instead of `simpleDispatcher` you can cache the generated\nrouting data and construct the dispatcher from the cached information:\n\n```php\n\u003c?php\n\n$dispatcher = FastRoute\\cachedDispatcher(function(FastRoute\\ConfigureRoutes $r) {\n    $r-\u003eaddRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0');\n    $r-\u003eaddRoute('GET', '/user/{id:[0-9]+}', 'handler1');\n    $r-\u003eaddRoute('GET', '/user/{name}', 'handler2');\n}, [\n    'cacheKey' =\u003e __DIR__ . '/route.cache', /* required */\n    // 'cacheFile' =\u003e __DIR__ . '/route.cache', /* will still work for v1 compatibility */\n    'cacheDisabled' =\u003e IS_DEBUG_ENABLED,     /* optional, enabled by default */\n    'cacheDriver' =\u003e FastRoute\\Cache\\FileCache::class, /* optional, class name or instance of the cache driver - defaults to file cache */\n]);\n```\n\nThe second parameter to the function is an options array, which can be used to specify the cache\nkey (e.g. file location when using files for caching), caching driver, among other things.\n\n### Dispatching a URI\n\nA URI is dispatched by calling the `dispatch()` method of the created dispatcher. This method\naccepts the HTTP method and a URI. Getting those two bits of information (and normalizing them\nappropriately) is your job - this library is not bound to the PHP web SAPIs.\n\nThe `dispatch()` method returns an array whose first element contains a status code. It is one\nof `Dispatcher::NOT_FOUND`, `Dispatcher::METHOD_NOT_ALLOWED` and `Dispatcher::FOUND`. For the\nmethod not allowed status the second array element contains a list of HTTP methods allowed for\nthe supplied URI. For example:\n\n    [FastRoute\\Dispatcher::METHOD_NOT_ALLOWED, ['GET', 'POST']]\n\n\u003e **NOTE:** The HTTP specification requires that a `405 Method Not Allowed` response include the\n`Allow:` header to detail available methods for the requested resource. Applications using FastRoute\nshould use the second array element to add this header when relaying a 405 response.\n\nFor the found status the second array element is the handler that was associated with the route\nand the third array element is a dictionary of placeholder names to their values. For example:\n\n    /* Routing against GET /user/nikic/42 */\n\n    [FastRoute\\Dispatcher::FOUND, 'handler0', ['name' =\u003e 'nikic', 'id' =\u003e '42']]\n\n### Overriding the route parser and dispatcher\n\nThe routing process makes use of three components: A route parser, a data generator and a\ndispatcher. The three components adhere to the following interfaces:\n\n```php\n\u003c?php\n\nnamespace FastRoute;\n\ninterface RouteParser {\n    public function parse($route);\n}\n\ninterface DataGenerator {\n    public function addRoute($httpMethod, $routeData, $handler);\n    public function getData();\n}\n\ninterface Dispatcher {\n    const NOT_FOUND = 0, FOUND = 1, METHOD_NOT_ALLOWED = 2;\n\n    public function dispatch($httpMethod, $uri);\n}\n```\n\nThe route parser takes a route pattern string and converts it into an array of route infos, where\neach route info is again an array of its parts. The structure is best understood using an example:\n\n    /* The route /user/{id:\\d+}[/{name}] converts to the following array: */\n    [\n        [\n            '/user/',\n            ['id', '\\d+'],\n        ],\n        [\n            '/user/',\n            ['id', '\\d+'],\n            '/',\n            ['name', '[^/]+'],\n        ],\n    ]\n\nThis array can then be passed to the `addRoute()` method of a data generator. After all routes have\nbeen added the `getData()` of the generator is invoked, which returns all the routing data required\nby the dispatcher. The format of this data is not further specified - it is tightly coupled to\nthe corresponding dispatcher.\n\nThe dispatcher accepts the routing data via a constructor and provides a `dispatch()` method, which\nyou're already familiar with.\n\nThe route parser can be overwritten individually (to make use of some different pattern syntax),\nhowever the data generator and dispatcher should always be changed as a pair, as the output from\nthe former is tightly coupled to the input of the latter. The reason the generator and the\ndispatcher are separate is that only the latter is needed when using caching (as the output of\nthe former is what is being cached.)\n\nWhen using the `simpleDispatcher` / `cachedDispatcher` functions from above the override happens\nthrough the options array:\n\n```php\n\u003c?php\n\n$dispatcher = FastRoute\\simpleDispatcher(function(FastRoute\\ConfigureRoutes $r) {\n    /* ... */\n}, [\n    'routeParser' =\u003e 'FastRoute\\\\RouteParser\\\\Std',\n    'dataGenerator' =\u003e 'FastRoute\\\\DataGenerator\\\\MarkBased',\n    'dispatcher' =\u003e 'FastRoute\\\\Dispatcher\\\\MarkBased',\n]);\n```\n\nThe above options array corresponds to the defaults. By replacing `MarkBased` with\n`GroupCountBased` you could switch to a different dispatching strategy.\n\n### A Note on HEAD Requests\n\nThe HTTP spec requires servers to [support both GET and HEAD methods][2616-511]:\n\n\u003e The methods GET and HEAD MUST be supported by all general-purpose servers\n\nTo avoid forcing users to manually register HEAD routes for each resource we fallback to matching an\navailable GET route for a given resource. The PHP web SAPI transparently removes the entity body\nfrom HEAD responses so this behavior has no effect on the vast majority of users.\n\nHowever, implementers using FastRoute outside the web SAPI environment (e.g. a custom server) MUST\nNOT send entity bodies generated in response to HEAD requests. If you are a non-SAPI user this is\n*your responsibility*; FastRoute has no purview to prevent you from breaking HTTP in such cases.\n\nFinally, note that applications MAY always specify their own HEAD method route for a given\nresource to bypass this behavior entirely.\n\n### Credits\n\nThis library is based on a router that [Levi Morrison][levi] implemented for the Aerys server.\n\nA large number of tests, as well as HTTP compliance considerations, were provided by [Daniel Lowrey][rdlowrey].\n\n\n[2616-511]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1 \"RFC 2616 Section 5.1.1\"\n[blog_post]: http://nikic.github.io/2014/02/18/Fast-request-routing-using-regular-expressions.html\n[levi]: https://github.com/morrisonlevi\n[rdlowrey]: https://github.com/rdlowrey\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnikic%2FFastRoute","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnikic%2FFastRoute","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnikic%2FFastRoute/lists"}