{"id":16414764,"url":"https://github.com/amranich/ajax-router","last_synced_at":"2025-03-23T06:31:26.467Z","repository":{"id":56947354,"uuid":"423015533","full_name":"AmraniCh/ajax-router","owner":"AmraniCh","description":"URL query string-based routing library with PSR-7 support. ","archived":false,"fork":false,"pushed_at":"2024-12-03T11:05:16.000Z","size":90,"stargazers_count":11,"open_issues_count":0,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-18T18:42:35.530Z","etag":null,"topics":["ajax","ajax-dispatcher","ajax-requests","ajax-router","http","php","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/AmraniCh.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","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":"2021-10-31T00:00:12.000Z","updated_at":"2025-02-06T09:17:18.000Z","dependencies_parsed_at":"2023-12-04T16:54:21.513Z","dependency_job_id":null,"html_url":"https://github.com/AmraniCh/ajax-router","commit_stats":{"total_commits":66,"total_committers":3,"mean_commits":22.0,"dds":"0.43939393939393945","last_synced_commit":"362969fb2af0944a4449ebe277d350de111a69a9"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmraniCh%2Fajax-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmraniCh%2Fajax-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmraniCh%2Fajax-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AmraniCh%2Fajax-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AmraniCh","download_url":"https://codeload.github.com/AmraniCh/ajax-router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245066496,"owners_count":20555402,"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":["ajax","ajax-dispatcher","ajax-requests","ajax-router","http","php","router"],"created_at":"2024-10-11T06:54:57.784Z","updated_at":"2025-03-23T06:31:25.782Z","avatar_url":"https://github.com/AmraniCh.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![packagist](https://img.shields.io/packagist/v/AmraniCh/ajax-router?include_prereleases)](https://packagist.org/packages/amranich/ajax-router)\n[![tests](https://github.com/AmraniCh/ajax-dispatcher/actions/workflows/tests.yml/badge.svg)](https://github.com/AmraniCh/ajax-dispatcher/actions/workflows/tests.yml)\n![License](https://img.shields.io/packagist/l/AmraniCh/ajax-router)\n\n\n## Getting Started\n\n```bash\ncomposer require amranich/ajax-router\n```\n\nYou can copy/paste this code snippet for a quick start.\n\nWe're using [Guzzle PSR-7 interface implementation](https://github.com/guzzle/psr7) here, but you can use any other library you like as long as it implements the same interface.\n\n```php\n\u003c?php\n\nrequire __DIR__ . '/vendor/autoload.php';\n\nuse GuzzleHttp\\Psr7\\Request;\nuse GuzzleHttp\\Psr7\\Response;\nuse AmraniCh\\AjaxRouter\\Route;\nuse AmraniCh\\AjaxRouter\\Router;\nuse AmraniCh\\AjaxRouter\\Dispatcher;\nuse GuzzleHttp\\Psr7\\ServerRequest;\nuse Lazzard\\Psr7ResponseSender\\Sender;\n\ntry {\n    $request = ServerRequest::fromGlobals();\n    \n    // the 'X-requested-with' header is commonly used to inform the server that a request \n    // is sent via the XMLHttpRequest object on the client-side, a lot of JavaScript libraries \n    // like jQuery already send this header automatically, this check can add a small security\n    // layer to your app because HTTP headers can be spoofed very easily, so don't count on\n    // only that check.\n    if (!$request-\u003ehasHeader('X-requested-with') \n        || strtolower($request-\u003egetHeader('X-requested-with')[0]) !== 'XMLHttpRequest') {\n        throw new BadRequestException(\"Accept only AJAX requests.\");\n    }\n    \n    // to organize your project, you can put your routes in a separate file like in an array\n    // and require it in the second parameter of the router constructor.  \n    $router = new Router($request, 'route', [\n    \n        // ?route=getPost\u0026id=1005\n        Route::get('getPost', function ($params) {\n        \n            // PSR7 responses are a little annoying to work with, you always have extra HTTP layers \n            // in your app that extend the base PSR7 response class, think of a class like JsonResponse, \n            // and in the constructor add the content-type header and pass it to the parent class.\n            $response = new Response;\n\n            $response-\u003egetBody()-\u003ewrite(json_encode([\n                'id' =\u003e $params['id'],\n                'title' =\u003e 'Best Places to Visit in Marrakech',\n                'description' =\u003e 'Example of post description',\n                'created_at' =\u003e '2022-02-27 03:00:05'\n            ]));\n\n            return $response-\u003ewithHeader('Content-type', 'application/json');\n        }),\n    ]);\n\n    $dispatcher = new Dispatcher($router);\n    $dispatcher-\u003edispatch();\n\n} catch (Exception $ex) {\n    $response = new Response(\n        $ex-\u003egetCode() ?: 500,\n        ['Content-type' =\u003e 'application/json'],\n        json_encode(['message' =\u003e $ex-\u003egetMessage()])\n    );\n\n    $sender = new Sender;\n    $sender($response);\n}\n```\n\n## Usage Tips\n\n### Route to controller/class method\n\nIf you like to put the business logic in a separate class or in a controller, you can route your requests to them like this :\n\n```php\nRoute::get('getPost', [PostController::class, 'getPost']);\n```\n\nOr :\n\n```php\nRoute::get('getPost', 'PostController@getPost');\n\n// register the controller class or instance in the router\n$router-\u003eregisterControllers([\n    PostController::class,\n]);\n```\n\nIf the controller/class has some dependencies that must be passed within the constructor, you can still instantiate the\ncontroller on yourself :\n\n```php\n$router-\u003eregisterControllers([\n    new PostController($dependencyOne, $dependencyTwo)\n]);\n```\n\n### Catch route actions exceptions\n\n*I want to catch exceptions that only occurs from my routes actions, and not those thrown by the library or somewhere else, how I can\ndo that ?*\n\nAnswer :\n\n```php\n$dispatcher-\u003eonException(function (\\Exception $ex) {\n    // $ex exception thrown by a route action\n});\n```\n\n### Get current route\n\nYou can access the current route object using the static method `getCurrentRoute` of the `Route` class.\n\n```php\n$route = Router::getCurrentRoute();\n$route-\u003egetName();\n$route-\u003egetMethods();\n$route-\u003egetValue();\n\n```\n\n## Background\n\nThe idea of the library came to my mind a long time ago when I was mostly developing web applications using just plain PHP, some of these applications were performing a lot of AJAX requests into a single PHP file, that file can have a hundred lines of code that process these requests depending on a function/method name that sent along with the request, so I started to think of what I can do to improve the way that these requests are handled, and improve the code readability and maintainability.\n\n## Prizes\n\nThis package wins the PHP Innovation Award (February 2022) Issued by phpclasses.org \n\n🏆 Prize :\nOne elePHPant mascot.\nhttps://www.php.net/elephpant.php\n\n📜 Certificate :\nhttps://amranich.dev/certs/phpclasses-february-2022-innovation-award.pdf\n\n## They support this project\n\n\u003cimg width=\"150px\" src=\"https://resources.jetbrains.com/storage/products/company/brand/logos/jb_square.png\"/\u003e\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famranich%2Fajax-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Famranich%2Fajax-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famranich%2Fajax-router/lists"}