{"id":18309804,"url":"https://github.com/phpdevcommunity/php-router","last_synced_at":"2025-08-10T12:20:17.658Z","repository":{"id":41938571,"uuid":"130552602","full_name":"phpdevcommunity/php-router","owner":"phpdevcommunity","description":"PHP Router is a simple and efficient routing library designed for PHP applications. It provides a straightforward way to define routes, handle HTTP requests, and generate URLs. Built with PSR-7 message implementation in mind, it seamlessly integrates with PHP applications.","archived":false,"fork":false,"pushed_at":"2025-04-01T15:29:55.000Z","size":150,"stargazers_count":26,"open_issues_count":0,"forks_count":5,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-01T16:09:38.088Z","etag":null,"topics":["php","php-library","psr-7","request","router"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/phpdevcommunity.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":"2018-04-22T09:20:06.000Z","updated_at":"2025-04-01T15:29:15.000Z","dependencies_parsed_at":"2024-03-31T21:30:33.775Z","dependency_job_id":"400b4049-3c1c-4f1c-a7b1-323a4c8f0146","html_url":"https://github.com/phpdevcommunity/php-router","commit_stats":{"total_commits":28,"total_committers":6,"mean_commits":4.666666666666667,"dds":0.4642857142857143,"last_synced_commit":"94301ce1a8a698012a1ec9f4c33a78765d561844"},"previous_names":["phpdevcommunity/php-router","devcoder-xyz/php-router"],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/phpdevcommunity%2Fphp-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/phpdevcommunity%2Fphp-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/phpdevcommunity%2Fphp-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/phpdevcommunity%2Fphp-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/phpdevcommunity","download_url":"https://codeload.github.com/phpdevcommunity/php-router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247375652,"owners_count":20929073,"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":["php","php-library","psr-7","request","router"],"created_at":"2024-11-05T16:12:27.905Z","updated_at":"2025-08-10T12:20:17.645Z","avatar_url":"https://github.com/phpdevcommunity.png","language":"PHP","readme":"# PHP Router\n\nPHP Router is a simple and efficient routing library designed for PHP applications. It provides a straightforward way to\ndefine routes, handle HTTP requests, and generate URLs. Built with PSR-7 message implementation in mind, it seamlessly\nintegrates with PHP applications.\n\n## Installation\n\nYou can install PHP Router via Composer. Just run:\n\n### Composer Require\n\n```\ncomposer require phpdevcommunity/php-router\n```\n\n## Requirements\n\n* PHP version 7.4 or above\n* Enable URL rewriting on your web server\n* Optional: PSR-7 HTTP Message package (e.g., guzzlehttp/psr7)\n\n## Usage\n\n1. **Define Routes**: Define routes using the `Route` class provided by PHP Router.\n\n2. **Initialize Router**: Initialize the `Router` class with the defined routes.\n\n3. **Match Requests**: Match incoming HTTP requests to defined routes.\n\n4. **Handle Requests**: Handle matched routes by executing appropriate controllers or handlers.\n\n5. **Generate URLs**: Generate URLs for named routes.\n\n## Example\n\n```php\n\u003c?php\nclass IndexController {\n\n    // PHP \u003e 8.0\n    #[\\PhpDevCommunity\\Attribute\\Route(path: '/', name: 'home_page')]\n    public function __invoke()\n    {\n        return 'Hello world!!';\n    }\n}\n\nclass ArticleController {\n   // PHP \u003e 8.0\n    #[\\PhpDevCommunity\\Attribute\\Route(path: '/api/articles', name: 'api_articles_collection')]\n    public function getAll()\n    {\n        // db get all post\n        return json_encode([\n            ['id' =\u003e 1],\n            ['id' =\u003e 2],\n            ['id' =\u003e 3]\n        ]);\n    }\n    // PHP \u003e 8.0\n    #[\\PhpDevCommunity\\Attribute\\Route(path: '/api/articles/{id}', name: 'api_articles')]\n    public function get(int $id)\n    {\n        // db get post by id\n        return json_encode(['id' =\u003e $id]);\n    }\n\n    public function put(int $id)\n    {\n        // db edited post by id\n        return json_encode(['id' =\u003e $id]);\n    }\n\n    public function post()\n    {\n        // db create post\n        return json_encode(['id' =\u003e 4]);\n    }\n}\n```\n\n```php\n// Define your routes\n\nif (PHP_VERSION_ID \u003e= 80000) {\n    $attributeRouteCollector = new AttributeRouteCollector([\n        IndexController::class,\n        ArticleController::class\n    ]);\n    $routes = $attributeRouteCollector-\u003ecollect();\n}else {\n    $routes = [\n        new \\PhpDevCommunity\\Route('home_page', '/', [IndexController::class]),\n        new \\PhpDevCommunity\\Route('api_articles_collection', '/api/articles', [ArticleController::class, 'getAll']),\n        new \\PhpDevCommunity\\Route('api_articles', '/api/articles/{id}', [ArticleController::class, 'get']),\n    ];\n}\n\n// Initialize the router\n$router = new \\PhpDevCommunity\\Router($routes, 'http://localhost');\n\ntry {\n    // Match incoming request\n    $route = $router-\u003ematch(ServerRequestFactory::fromGlobals());\n    \n    // Handle the matched route\n    $handler = $route-\u003egetHandler();\n    $attributes = $route-\u003egetAttributes();\n    $controllerName = $handler[0];\n    $methodName = $handler[1] ?? null;\n    $controller = new $controllerName();\n    \n    // Invoke the controller method\n    if (!is_callable($controller)) {\n        $controller =  [$controller, $methodName];\n    }\n    echo $controller(...array_values($attributes));\n\n} catch (\\PhpDevCommunity\\Exception\\MethodNotAllowed $exception) {\n    header(\"HTTP/1.0 405 Method Not Allowed\");\n    exit();\n} catch (\\PhpDevCommunity\\Exception\\RouteNotFound $exception) {\n    header(\"HTTP/1.0 404 Not Found\");\n    exit();\n}\n```\n\n## Features\n\n- Lightweight and easy-to-use\n- Supports HTTP method-based routing\n- Flexible route definition with attribute constraints\n- Exception handling for method not allowed and route not found scenarios\n\n## Route Definition\n\nRoutes can be defined using the `Route` class provided by PHP Router. You can specify HTTP methods, attribute\nconstraints, and handler methods for each route.\n\n```php\n$route = new \\PhpDevCommunity\\Route('api_articles_post', '/api/articles', [ArticleController::class, 'post'], ['POST']);\n$route = new \\PhpDevCommunity\\Route('api_articles_put', '/api/articles/{id}', [ArticleController::class, 'put'], ['PUT']);\n```\n\n### Easier Route Definition with Static Methods\n\nTo make route definition even simpler and more intuitive, the `RouteTrait` provides static methods for creating\ndifferent types of HTTP routes. Here's how to use them:\n\n#### Method `get()`\n\n```php\n/**\n * Creates a new GET route with the given name, path, and handler.\n *\n * @param string $name The name of the route.\n * @param string $path The path of the route.\n * @param mixed $handler The handler for the route.\n * @return BaseRoute The newly created GET route.\n */\npublic static function get(string $name, string $path, $handler): BaseRoute\n{\n    return new BaseRoute($name, $path, $handler);\n}\n```\n\nExample Usage:\n\n```php\n$route = Route::get('home', '/', [HomeController::class, 'index']);\n```\n\n#### Method `post()`\n\n```php\n/**\n * Creates a new POST route with the given name, path, and handler.\n *\n * @param string $name The name of the route.\n * @param string $path The path of the route.\n * @param mixed $handler The handler for the route.\n * @return BaseRoute The newly created POST route.\n */\npublic static function post(string $name, string $path, $handler): BaseRoute\n{\n    return new BaseRoute($name, $path, $handler, ['POST']);\n}\n```\n\nExample Usage:\n\n```php\n$route = Route::post('submit_form', '/submit', [FormController::class, 'submit']);\n```\n\n#### Method `put()`\n\n```php\n/**\n * Creates a new PUT route with the given name, path, and handler.\n *\n * @param string $name The name of the route.\n * @param string $path The path of the route.\n * @param mixed $handler The handler for the route.\n * @return BaseRoute The newly created PUT route.\n */\npublic static function put(string $name, string $path, $handler): BaseRoute\n{\n    return new BaseRoute($name, $path, $handler, ['PUT']);\n}\n```\n\nExample Usage:\n\n```php\n$route = Route::put('update_item', '/item/{id}', [ItemController::class, 'update']);\n```\n\n#### Method `delete()`\n\n```php\n/**\n * Creates a new DELETE route with the given name, path, and handler.\n *\n * @param string $name The name of the route.\n * @param string $path The path of the route.\n * @param mixed $handler The handler for the route.\n * @return BaseRoute The newly created DELETE route.\n */\npublic static function delete(string $name, string $path, $handler): BaseRoute\n{\n    return new BaseRoute($name, $path, $handler, ['DELETE']);\n}\n```\n\nExample Usage:\n\n```php\n$route = Route::delete('delete_item', '/item/{id}', [ItemController::class, 'delete']);\n```\n\n### Using `where` Constraints in the Route Object\n\nThe `Route` object allows you to define constraints on route parameters using the `where` methods. These constraints\nvalidate and filter parameter values based on regular expressions. Here's how to use them:\n\n#### Method `whereNumber()`\n\nThis method applies a numeric constraint to the specified route parameters.\n\n```php\n/**\n * Sets a number constraint on the specified route parameters.\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereNumber(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, '[0-9]+');\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('example', '/example/{id}'))-\u003ewhereNumber('id');\n```\n\n#### Method `whereSlug()`\n\nThis method applies a slug constraint to the specified route parameters, allowing alphanumeric characters and hyphens.\n\n```php\n/**\n * Sets a slug constraint on the specified route parameters.\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereSlug(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, '[a-z0-9-]+');\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('article', '/article/{slug}'))-\u003ewhereSlug('slug');\n```\n\n#### Method `whereAlphaNumeric()`\n\nThis method applies an alphanumeric constraint to the specified route parameters.\n\n```php\n/**\n * Sets an alphanumeric constraint on the specified route parameters.\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereAlphaNumeric(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, '[a-zA-Z0-9]+');\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('user', '/user/{username}'))-\u003ewhereAlphaNumeric('username');\n```\n\n#### Method `whereAlpha()`\n\nThis method applies an alphabetic constraint to the specified route parameters.\n\n```php\n/**\n * Sets an alphabetic constraint on the specified route parameters.\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereAlpha(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, '[a-zA-Z]+');\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('category', '/category/{name}'))-\u003ewhereAlpha('name');\n```\n\n#### Method `whereTwoSegments()`\n\nThis method applies a constraint to match exactly two path segments separated by a slash.\n\n```php\n/**\n * Sets a constraint for exactly two path segments separated by a slash.\n *\n * Example: /{segment1}/{segment2}\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereTwoSegments(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, '[a-zA-Z0-9\\-_]+/[a-zA-Z0-9\\-_]+');\n    foreach ($parameters as $parameter) {\n        $this-\u003epath = str_replace(sprintf('{%s}', $parameter), sprintf('{%s*}', $parameter), $this-\u003epath);\n    }\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('profile', '/profile/{username}/{id}'))-\u003ewhereTwoSegments('username', 'id');\n```\n\n#### Method `whereAnything()`\n\nThis method applies a constraint to match any characters.\n\n```php\n/**\n * Sets a constraint to match any characters.\n *\n * Example: /{anyPath}\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereAnything(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, '.+');\n    foreach ($parameters as $parameter) {\n        $this-\u003epath = str_replace(sprintf('{%s}', $parameter), sprintf('{%s*}', $parameter), $this-\u003epath);\n    }\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('any', '/{anyPath}'))-\u003ewhereAnything('anyPath');\n```\n\n#### Method `whereDate()`\n\nThis method applies a date constraint to the specified route parameters, expecting a format `YYYY-MM-DD`.\n\n```php\n/**\n * Sets a date constraint on the specified route parameters.\n *\n * Example: /{date}\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereDate(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, '\\d{4}-\\d{2}-\\d{2}');\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('date', '/date/{date}'))-\u003ewhereDate('date');\n```\n\n#### Method `whereYearMonth()`\n\nThis method applies a year-month constraint to the specified route parameters, expecting a format `YYYY-MM`.\n\n```php\n/**\n * Sets a year/month constraint on the specified route parameters.\n *\n * Example: /{yearMonth}\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereYearMonth(...$parameters): self\n{\n        $this-\u003eassignExprToParameters($parameters, '\\d{4}-\\d{2}');\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('yearMonth', '/yearMonth/{yearMonth}'))-\u003ewhereYearMonth('yearMonth');\n```\n\n#### Method `whereEmail()`\n\nThis method applies an email constraint to the specified route parameters.\n\n```php\n/**\n * Sets an email constraint on the specified route parameters.\n *\n * Example: /{email}\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereEmail(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}');\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('user', '/user/{email}'))-\u003ewhereEmail('email');\n```\n\n#### Method `whereUuid()`\n\nThis method applies a UUID constraint to the specified route parameters.\n\n```php\n/**\n * Sets a UUID constraint on the specified route parameters.\n *\n * Example: /{uuid}\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereUuid(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}');\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('profile', '/profile/{uuid}'))-\u003ewhereUuid('uuid');\n```\n\n#### Method `whereBool()`\n\nThis method applies a boolean constraint to the specified route parameters, accepting `true`, `false`, `1`, and `0`.\n\n```php\n/**\n * Sets a boolean constraint on the specified route parameters.\n *\n * Example: /{isActive}\n *\n * @param mixed ...$parameters The route parameters to apply the constraint to.\n * @return self The updated Route instance.\n */\npublic function whereBool(...$parameters): self\n{\n    $this-\u003eassignExprToParameters($parameters, 'true|false|1|0');\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('status', '/status/{isActive}'))-\u003ewhereBool('isActive');\n```\n\n#### Method `where()`\n\nThis method allows you to define a custom constraint on a specified route parameter.\n\n```php\n/**\n * Sets a custom constraint on the specified route parameter.\n *\n * @param string $parameter The route parameter to apply the constraint to.\n * @param string $expression The regular expression constraint.\n * @return self The updated Route instance.\n */\npublic function where(string $parameter, string $expression): self\n{\n    $this-\u003ewheres[$parameter] = $expression;\n    return $this;\n}\n```\n\nExample Usage:\n\n```php\n$route = (new Route('product', '/product/{code}'))-\u003ewhere('code', '\\d{4}');\n```\n\nBy using these `where` methods, you can apply precise constraints on your route parameters, ensuring proper validation\nof input values.\n\n## Generating URLs\n\nGenerate URLs for named routes using the `generateUri` method.\n\n```php\necho $router-\u003egenerateUri('home_page'); // /\necho $router-\u003egenerateUri('api_articles', ['id' =\u003e 1]); // /api/articles/1\necho $router-\u003egenerateUri('api_articles', ['id' =\u003e 1], true); // http://localhost/api/articles/1\n```\n\n## Contributing\n\nContributions are welcome! Feel free to open issues or submit pull requests to help improve the library.\n\n## License\n\nThis library is open-source software licensed under the [MIT license](https://opensource.org/licenses/MIT).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fphpdevcommunity%2Fphp-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fphpdevcommunity%2Fphp-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fphpdevcommunity%2Fphp-router/lists"}