{"id":24767125,"url":"https://github.com/leven-framework/router","last_synced_at":"2025-03-23T18:43:58.328Z","repository":{"id":43697880,"uuid":"442421874","full_name":"leven-framework/router","owner":"leven-framework","description":"🛣️ configure routes using PHP8 attributes, support for reverse routing, before and after middlewares and more","archived":false,"fork":false,"pushed_at":"2022-07-12T18:03:31.000Z","size":607,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-29T00:52:42.309Z","etag":null,"topics":["dependency-injection","middleware","php","php-attributes","php8","router","routing"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/leven-framework.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-12-28T10:02:08.000Z","updated_at":"2023-09-06T09:53:56.000Z","dependencies_parsed_at":"2022-09-17T00:11:35.127Z","dependency_job_id":null,"html_url":"https://github.com/leven-framework/router","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leven-framework%2Frouter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leven-framework%2Frouter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leven-framework%2Frouter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leven-framework%2Frouter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/leven-framework","download_url":"https://codeload.github.com/leven-framework/router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245153085,"owners_count":20569399,"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":["dependency-injection","middleware","php","php-attributes","php8","router","routing"],"created_at":"2025-01-29T00:52:20.072Z","updated_at":"2025-03-23T18:43:58.298Z","avatar_url":"https://github.com/leven-framework.png","language":"PHP","readme":"# Leven Router\n\n## Features\n- 📝 route parameters\n- 🪹 nestable route groups\n- 🔧 configure routes with PHP8 attributes\n- 💉 dependency injection using [Auryn](https://github.com/rdlowrey/auryn)\n- 🔄 reverse routing (controller -\u003e path)\n- 🚥 middleware support (before and after)\n\n## Basic usage example\n\n```php\nrequire 'vendor/autoload.php';\n\n($injector = new \\Auryn\\Injector)-\u003eshare( $request = \\Leven\\Router\\Messages\\Request::fromSuperglobals() );\n$rc = new \\Leven\\Router\\RouterConfigurator( $router = new \\Leven\\Router\\Router );\n\n\n$rc-\u003epost('/demo', function(\\Leven\\Router\\Messages\\Request $request) {\n    return \"Hello {$request-\u003ebody-\u003ename}\";\n});\n\n$rc-\u003eget('/test/{id}', function(\\Leven\\Router\\RouteParams $params) {\n    return \"ID: {$params-\u003eid}\";\n});\n\n\n(new \\Leven\\Router\\RouteHandler($injector))-\u003ehandle($router-\u003ematch($request))-\u003edispatch();\n```\n\n## Attribute configuration + reverse routing example\n\n```php\nrequire 'vendor/autoload.php';\n\n($injector = new \\Auryn\\Injector)-\u003eshare( $request = \\Leven\\Router\\Messages\\Request::fromSuperglobals() );\n$router = new \\Leven\\Router\\Router;\n\n\nclass MyController {\n    #[\\Leven\\Router\\Route('GET', '/foo')]\n    public function fooController(){\n        return new \\Leven\\Router\\Messages\\JsonResponse(['foo' =\u003e 'hello']);\n    }\n    \n    #[\\Leven\\Router\\Route('GET', '/bar')]\n    public function barController(\\Leven\\Router\\RouteUrlResolver $url){\n        $href = $url([static::class, 'fooController']);\n        return new \\Leven\\Router\\Messages\\HtmlResponse(\"\u003ca href='$href'\u003efoo\u003c/a\u003e\");\n    }\n}\n\n(new \\Leven\\Router\\ControllerScanner($router))\n    -\u003escanControllerClasses(MyController::class, );\n   \n// RouteUrlResolver allows you to get route path of a given controller\n$injector-\u003eshare( new \\Leven\\Router\\RouteUrlResolver($router) );\n\n\n(new \\Leven\\Router\\RouteHandler($injector))-\u003ehandle($router-\u003ematch($request))-\u003edispatch();\n```\n\n## Middleware example\n\n```php\nrequire 'vendor/autoload.php';\n\n($injector = new \\Auryn\\Injector)-\u003eshare( $request = \\Leven\\Router\\Messages\\Request::fromSuperglobals() );\n$rc = new \\Leven\\Router\\RouterConfigurator( $router = new \\Leven\\Router\\Router );\n\n\nclass MyMiddleware {\n    function __invoke(\\Leven\\Router\\MiddlewareCallback $next) {\n        $response = $next();\n        return \"before $response-\u003ebody after\";\n    }\n}\n\n$rc-\u003epost('/cool', fn() =\u003e \"something\")-\u003emiddleware(MyMiddleware::class);\n\n\n(new \\Leven\\Router\\RouteHandler($injector))-\u003ehandle($router-\u003ematch($request))-\u003edispatch();\n```\n\n## Installation\n\nPHP 8.1+ is required.\n\n```sh\ncomposer install leven-framework/router\n```\n\n## Gotchas\n\n- You're locked into using [Auryn](https://github.com/rdlowrey/auryn) for dependency injection\n- No support for other Request or Response classes like PSR-7\n- There's no production optimization for scanned routes yet implemented\n- This readme is only documentation for now\n- No tests written yet\n\n## Documentation\n\n```php\n\u003c?php\n\nrequire 'vendor/autoload.php';\n\n// first we need to create a dependency injector; check https://github.com/rdlowrey/auryn for more info\n$injector = new \\Auryn\\Injector();\n\n// initialize a Request object automatically from the superglobals ($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER)\n$request = \\Leven\\Router\\Messages\\Request::fromSuperglobals();\n\n// here we share the Request object with the injector, so Auryn can inject it into our controllers\n$injector-\u003eshare($request);\n\n// this object will hold the route registry and perform route matching\n$router = new \\Leven\\Router\\Router;\n\n// you can optionally specify middleware to be prepended to each route's middleware stack\n$router-\u003eaddGlobalMiddleware( MyMiddleware::class, function( ){ }, [MyMiddleware::class, 'someMethod'], );\n\n\n\n// you can use the RouterConfigurator to easily add routes to the router\n$config = new \\Leven\\Router\\RouterConfigurator($router);\n\n$config-\u003eget('/demo/{id}', function( ){ });\n\n$config-\u003epost('/demo/{id}', Controller::class)\n    -\u003emiddlewareAppend(MyMiddleware::class);\n\n$config-\u003emap('PUT', '/test', [Controller::class, 'controllerMethod'])\n    -\u003emiddlewarePrepend([MyMiddleware::class, 'middlewareMethod']);\n\n$config-\u003emap(['GET', 'POST'], '/test/{uuid}', function( ){  })\n        -\u003emiddleware(function( ){ }); // alias for middlewareAppend\n\n$config-\u003egroup('/group', function(\\Leven\\Router\\RouterConfigurator $group){\n    $group-\u003eaddMiddleware(MyMiddleware::class);\n\n    $group-\u003eget('/inner', MyController::class); // path: /group/inner\n    \n    $group-\u003egroup('/deep', function(\\Leven\\Router\\RouterConfigurator $group2){\n        $group2-\u003eput('/foo', function( ){ }); // path: /group/deep/foo\n    });\n});\n\n\n\n// another way to define routes is by giving Route attributes to controller methods\n\nclass MyController {\n    #[\\Leven\\Router\\Route('GET', '/foo/{id}')]\n    public function __invoke( ) { /* ... */ }\n\n    #[\\Leven\\Router\\Route(['GET', 'POST'], '/bar/baz', middleware: [Middleware::class])]\n    public function controllerMethod( ) { /* ... */ }\n}\n\n// ControllerScanner will scan classes for methods with Route attributes and configure the Router accordingly\n$scanner = new \\Leven\\Router\\ControllerScanner($router);\n$scanner-\u003escanControllerClasses(MyController::class, );\n\n\n\n// RouteUrlResolver helps generate URLs by reverse matching a controller to a path\n$url = new \\Leven\\Router\\RouteUrlResolver($router);\n$url = new \\Leven\\Router\\RouteUrlResolver($router, prefix: '/api/v1/');\n$url = new \\Leven\\Router\\RouteUrlResolver($router, prefix: 'https://example.com/');\n\n// share the RouteUrlResolver, so it can be used in controllers\n$injector-\u003eshare($url);\n\n// in the controller, use RouteUrlResolver like this:\n$href = $url([MyController::class, 'controllerMethod']);\n// and your route has parameters, pass them as the second argument:\n$href = $url(MyController::class, ['id' =\u003e '123']);\n\n\n\n// when writing a controller, keep in mind all parameters\n// will be injected automatically by Auryn\nclass AnotherController {\n    // if your controller class has many controller methods,\n    // you can provide shared dependencies in the class constructor\n    public function __construct(\n        protected \\Leven\\Router\\RouteUrlResolver $url,\n        protected \\Leven\\Router\\Messages\\Request $request,\n    ){}\n    \n    public function __invoke( ) {\n        // access the dependencies from constructor:\n        $href = ($this-\u003eurl)(MyController::class);\n    }\n}\n\n\n\n// route parameters can be accessed in the controller through\n// the automatically injected RouteParams object\nfunction fooController(\\Leven\\Router\\RouteParams $params) {\n    return 'Hello ' . $params-\u003ename;\n}\n\n\n\n// middlewares control the flow of the request:\n// they can call the next middleware in the stack, or return a response\n\nfunction myMiddleware( \\Leven\\Router\\MiddlewareCallback $next ) {\n    // if you want to prevent the request from continuing, don't call $next()\n    // you can also modify the response returned by $next() before returning it\n    \n    return $next(); // this middleware doesn't do anything\n}\n\n\n\n// each controller should return a Response object\n// if a string is returned, it will be converted\n// into a Response object with the string as the body\nfunction myController() {\n    return new \\Leven\\Router\\Messages\\Response('Hello World!');\n    return 'Hello World!'; // same as above\n    \n    return new \\Leven\\Router\\Messages\\Response('wrong request', 400);\n    return new \\Leven\\Router\\Messages\\JsonResponse(['message' =\u003e 'foo']);\n    return new \\Leven\\Router\\Messages\\HtmlResponse('\u003ch1\u003eno access!\u003c/h1\u003e', '403');\n    return new \\Leven\\Router\\Messages\\RedirectResponse('/foo');\n}\n\n\n\n// the Request object has the following properties:\n$request-\u003emethod // HTTP request method as a string\n$request-\u003epath // path of the request as a string\n$request-\u003equery // query string as an array\n$request-\u003ebody // request body if any (decoded)\n$request-\u003erawBody // raw request body if any\n$request-\u003eheaders // request headers as an array\n$request-\u003ecookies // request cookies as an array\n$request-\u003efiles // request files as an array\n\n// requests also contain custom attributes that may be useful\n// for passing data between middleware and controllers\n$request-\u003esetAttribute($name, $value);\n$foo = $request-\u003egetAttribute($name);\n\n\n\n// after configuring the Router, we match the Request to resolve a Route\n// if no route is found, the Router will throw a RouteNotFoundException\ntry {\n    $matchedRoute = $router-\u003ematch($request);\n} catch (\\Leven\\Router\\Exception\\RouteNotFoundException $e) {\n    die('route not found');\n}\n\n\n\n// RouteHandler handles execution of a Route and its middleware stack\n$handler = new \\Leven\\Router\\RouteHandler($injector);\n\n// it returns a Response object that we can manipulate if needed\n$response = $handler-\u003ehandle($matchedRoute);\n\n// finally, we can send the response to the client\n$response-\u003edispatch();\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleven-framework%2Frouter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fleven-framework%2Frouter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleven-framework%2Frouter/lists"}