{"id":33987953,"url":"https://github.com/thecodezone/wp-router","last_synced_at":"2026-05-29T08:02:11.492Z","repository":{"id":214692558,"uuid":"737127300","full_name":"thecodezone/wp-router","owner":"thecodezone","description":"A FastRoute-based router for use in Roots-based WordPress plugins and themes or any plugin or theme that use Illuminate\\Container.","archived":false,"fork":false,"pushed_at":"2024-09-18T17:33:17.000Z","size":183,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-12-14T17:56:35.260Z","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":"gpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thecodezone.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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-12-29T22:51:21.000Z","updated_at":"2024-09-18T17:33:21.000Z","dependencies_parsed_at":null,"dependency_job_id":"ce156652-0d3d-4203-9124-0d3da52bc7d6","html_url":"https://github.com/thecodezone/wp-router","commit_stats":null,"previous_names":["thecodezone/wp-router"],"tags_count":33,"template":false,"template_full_name":null,"purl":"pkg:github/thecodezone/wp-router","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thecodezone%2Fwp-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thecodezone%2Fwp-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thecodezone%2Fwp-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thecodezone%2Fwp-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thecodezone","download_url":"https://codeload.github.com/thecodezone/wp-router/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thecodezone%2Fwp-router/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33631002,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-05-28T02:00:06.440Z","response_time":99,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":"2025-12-13T05:45:06.886Z","updated_at":"2026-05-29T08:02:11.464Z","avatar_url":"https://github.com/thecodezone.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CodeZone Router\n\nThis package contains a simple routing system implementation that works with Roots-based WordPress plugins or sites, or\nany WordPress projects that utilize container.\n\nThe router uses the FastRoute dispatching library and integrates with the `Illuminate\\Container\\Container` class from\nthe Laravel framework for managing dependencies.\n\n## Links\n\n- [Sage](https://roots.io/): The modern WordPress starter theme with a development workflow.\n- [FastRoute](https://github.com/nikic/FastRoute): A fast request router for PHP that is highly flexible and reverse\n  routing compatible.\n- [Illuminate Container](https://github.com/illuminate/container): The Illuminate Container package is used to manage\n  class dependencies and perform dependency injection, part of the Laravel framework.\n\n## Usage\n\nImport the Router class at the top of your PHP file:\n\n```php\nuse CodeZone\\Router;\n```\n\n### Registering the Router\n\nYou first have to register the router with a container. This can be done inside of a service provider or a plugin's main\nfile.\n\n```php\n$router = Router::register($configArray);\n```\n\nIn this example, `$configArray` is an array that must contain a `'container'` key with an instance\nof `Illuminate\\Container\\Container` as a value:\n\n```php\n$configArray = [\n    'container' =\u003e $containerInstance // Illuminate\\Container\\Container\n];\n```\n\n### Defining Routes\n\nOnce the router is registered, you can define routes via a callback function:\n\n```php\n$dispatcher = $router-\u003eroutes(function (Routes $r) {\n    $r-\u003eget('/my-route', [Plugin\\Controllers\\MyController::class, 'index']);\n    //or\n    $r-\u003eget('/my-route', 'Plugin\\Controllers\\MyController@index');\n    //or\n    $r-\u003eget('/my-route', function () {\n        return \"\u003ch1\u003eHello World!\u003c/h1\u003e\";\n    });\n});\n```\n\n### Route Parameters\n\nRoute parameters provide dynamic segments in routing paths and allow paths to contain variable parts. This package uses\nFastRoute syntax for defining route parameters.\n\nHere's an example of a route with a parameter:\n\n```php\n    $r-\u003eget('/user/{id}', 'Plugin\\Controllers\\UserController@show');\n```\n\nIn this case, `{id}` is a route parameter. When matching routes, FastRoute uses these parameters to capture parts of the\npath, which allows for flexible routing strategies.\n\nYou can read more about route parameters in the [FastRoute documentation](https://github.com/nikic/FastRoute).\n\n### Conditionals\n\nIn this routing system, you can define conditional routes using `$r-\u003econdition(conditionClass, callback)`.\nThe `conditionClass` must be a class that implements a `test()` method returning a boolean. The callback is only\nexecuted if the `test()` method returns `true`.\n\nHere is an example, where `IsFrontendPath` is a class that defines a condition for checking if the current request is\nnot directed at an admin page:\n\n```php\nnamespace CodeZone\\Router\\Conditions;\n\nclass IsFrontendPath implements Condition {\n    public function test(): bool {\n        return ! is_admin();\n    }\n}\n```\n\nYou would use it in your routes definition like this to exclude these routes from being registered on admin pages:\n\n```php\n$r-\u003econdition(IsFrontendPath::class, function($r){\n    $r-\u003eget('/my-route', 'MyController');\n});\n```\n\nYou may also use the `codezone/router/conditions` action to add named conditions:\n\n```php\nadd_action( Router::class . '\\\\' . 'conditions', function($conditions) {\n    $conditions['isFrontend'] = IsFrontendPath::class;\n});\n```\n\nThis allows for more reader-friendly route condition definitions:\n\n```php\n$r-\u003econdition('isFrontend', function($r){\n    $r-\u003eget('/my-route', 'MyController');\n});\n```\n\nIn this scenario, a GET request to '/my-route' is handled by the `'MyController'` handler only if the `IsFrontendPath`\ncondition is met, that is, only if the request is not an admin request.\n\n### Middleware\n\nMiddleware in this routing system provides a set of \"layers\" through which a request must pass before it reaches your\napplication handlers, and through which the response must pass on the way back.\n\nMiddleware can be used to modify the HTTP request or response, for instance, or to run code before or after the request\nhandling.\n\nAn example of middleware usage is a `LoggedIn` class, which checks if a user is logged in:\n\n```php\nnamespace CodeZone\\Router\\Middleware;\n\nuse CodeZone\\Router\\Illuminate\\Http\\Request;\nuse WP_HTTP_Response;\n\nclass LoggedIn implements Middleware {\n\n    public function handle( Request $request, WP_HTTP_Response $response, $next ) {\n    \n        if ( ! is_user_logged_in() ) {\n            $response-\u003eset_status( 302 );\n            $response-\u003eset_data( wp_login_url( $request-\u003egetUri() ) );\n        }\n\n        return $next( $request, $response );\n    }\n}\n```\n\nIn this example, if the user is not logged in, the middleware sets the response status to 302 and redirects the user to\nthe login page. Otherwise, it continues the middleware stack to the next middleware.\n\n#### Global Middleware\n\nGlobal middleware is applied to all routes and is registered by adding Middleware to a `Stack`, which extends Laravel\ncollections.\n\nCreating a new stack is done by passing an array of middleware class names to the `Stack` constructor. The following\nstack will process the entire request / response lifecycle of your theme or plugin.\n\n```php\nuse CodeZone\\Router\\Middleware\\DispatchController;\nuse CodeZone\\Router\\Middleware\\HandleErrors;\nuse CodeZone\\Router\\Middleware\\HandleRedirects;\nuse CodeZone\\Router\\Middleware\\Render;\nuse CodeZone\\Router\\Middleware\\Route;\nuse CodeZone\\Router\\Middleware\\SetHeaders;\nuse CodeZone\\Router\\Middleware\\Stack;\n\n$middleware = [\n    Route::class,\n    DispatchController::class,\n    SetHeaders::class,\n    HandleRedirects::class,\n    HandleErrors::class,\n    Render::class,\n];\n\n$stack = container()-\u003emakeWith(Stack::class, $middleware);\n\n$stack-\u003erun();\n```\n\nOnce you have a Stack instance, you can push middleware classes onto it, to create a stack (or pipeline) of middleware\nthat your application will run through. The request will move through the stack in the order that middleware is added.\nThe added middleware wrap around your application handling, allowing them to interact with the request before and after\nthe application does.\n\n#### Route Middleware\n\nIn addition to global middleware that runs for every route, you can define middleware that runs only for specific\nroutes.\n\nYou can apply route middleware by chaining the `-\u003emiddleware()` method after defining a route:\n\n```php\n$r-\u003eget('/my-route', 'MyController')-\u003emiddleware(Middleware::class);\n```\n\nIn this example, `Middleware::class` will only be applied to the '/my-route' route.\n\nNote that like conditionals, you can pass a callback to the `middleware()` method:\n\n```php\n$r-\u003eget('/my-route', 'MyController')-\u003emiddleware(Middleware::class, function () {\n//...\n});\n```\n\nThe second way to apply middleware to a route is by including it in the third value of the handler array:\n\n```php\n$r-\u003eget('/my-route', ['MyController', 'myMethod', ['middleware' =\u003e Middleware::class]]);\n//or\n$r-\u003eget('/my-route', 'MyController')-\u003emiddleware([MiddlewareOne::class, MiddlewareTwo::class]);\n```\n\nIn this example, `Middleware::class` is applied to just the `/my-route` route.\n\nThese methods allow you to specify middleware that should only be executed for certain routes. This gives you more\nfine-grained control over when different middleware should be used in your plugin.\n\n#### Named Middleware\n\nYou may also use the `codezone/router/middleware` action to add named middleware:\n\n```php\nadd_action( Router::class . '\\\\' . 'middleware', function($middleware) {\n    $middleware['auth'] = AuthMiddleware::class;\n});\n```\n\nThis allows for more reader-friendly route middleware definitions:\n\n```php\n$r-\u003eget('/my-route', 'MyController', ['middleware' =\u003e 'auth']);\n```\n\nor\n\n```php\n$r-\u003emiddleware('auth', function($r){\n    $r-\u003eget('/my-route', 'MyController');\n});\n```\n\n##### HasCap Middleware\n\nThis package includes a `UserHasCap` middleware class that checks if the current user has a specific capability. You can\nuse this middleware to restrict access to certain routes.\n\nAssuming you register the named middleware as `['can' =\u003e UserHasCap::class]`, you can use it like this:\n\n```php\n$r-\u003eget('/my-route', 'MyController', ['middleware' =\u003e 'hasCap:manage_options,edit_posts']);\n```\n\n## WordPress Hooks\n\nThis package uses the `apply_filters` function to give you control over certain functionalities. Below are the hooks you\ncan use along with their descriptions.\n\n### 'codezone/router/response' filter\n\nThis filter modifies the HTTP response from the router:\n\n```php\nadd_filter( Router::class . '\\\\' . 'response', function($response) {\n    return $response;\n});\n```\n\n### 'codezone/router/error-codes' filter\n\nThis filter is used to modify the error codes.\n\n```php\nadd_filter( Router::class . '\\\\' . 'error_codes', function($error_codes) {\n    unset($error_codes[404]);\n    return $error_codes\n});\n```\n\n### 'codezone/router/routable_params' filter\n\nThis filter allows you to modify the routable parameters in the router. These parameters are considered part of the\nroute's path instead of only being passed to the `Request` object.\n\n```php\n    add_filter(Router::class . '\\\\' . 'routable_params', function($params) {\n        $params['action', 'page', 'tab'];\n    });\n\n    // Would match\n\n    $r-\u003eget('/contact?action=submit', 'Plugin\\Controllers\\ContactController@submit');\n```\n\n### 'codezone/router/routes' filter\n\nThis filter allows you to modify the routes in the router:\n\n```php\nadd_filter(Router::class . '\\\\' . 'routes', function($routes) {\n    $routes-\u003eget('/my-route', 'MyController');\nreturn $routes;\n});\n```\n\n### 'codezone/router/matched_routes' filter\n\nThis filter allows you to modify the matched routes in the router:\n\n```php\nadd_filter(Router::class . '\\\\' . 'matched_routes', function($matchedRoutes) {\n    $matchedRoutes[0] =  true;\n    $matchedRoutes[1] =  [\n        'handler' =\u003e [\n           'Plugin\\Controllers\\MyController'\n           'myMethod'\n        ],\n        'params' =\u003e [\n            'id' =\u003e '3',\n        ]\n    ]\n    return $matchedRoute;\n});\n```\n\n### 'codezone/router/render' action\n\nAn action to render the response. This action is called after the router has matched a route and before the response is\nsent to the browser.\n\n```php\nadd_action( Router::class . '\\\\' . 'render' ), function($response) {\n    echo $response-\u003egetContent();\n});\n```\n\n### 'codezone/router/render/json' action\n\nAn action to render the response as JSON. This action is called after the router has matched a route and before the\nresponse is sent to the browser.\n\n```php\nadd_action(Router::class . '\\\\' . 'render_json', function($response) {\n    echo json_encode($response-\u003egetContent());\n});\n```\n\n### 'codezone/router/middleware' action\n\nAn action for adding named middleware. Allows for more reader-friendly route middleware definitions.\n\n```php\nadd_action(Router::class . '\\\\' . 'middleware', function($middleware) {\n    $middleware['auth'] = AuthMiddleware::class;\n});\n```\n\n### 'codezone/router/conditions' action\n\nAn action for adding named conditions. Allows for more reader-friendly route condition definitions.\n\n```php\nadd_action(Router::class . '\\\\' . 'conditions', function($conditions) {\n    $conditions['isFrontend'] = IsFrontendPath::class;\n});\n```\n\n### 'codezone/router/conditions/factory' filter\n\nA filter for manually handling the instantiation of named conditions. Use this filter if you need to pass extra\nto parse the condition signature and pass extra parameters to the condition constructor.\n\n```php\nadd_filter(Router::class . '\\\\' . 'conditions_factory', function(Condition|null $instanceOrNull, array $attributes = []) {\n    //Check if this is our named condition\n    if ($name !== 'can') {\n        return $instanceOrNull;\n    }\n    \n    $className = $attributes['className'] ?? null;\n    $name = $attributes['name'] ?? null;\n    $signature = $attributes['signature'] ?? null;\n    \n    //The signature is the part of the route name after the \":\". We need to break it into an array.\n    $params = explode(',', $signature);\n    \n    return container-\u003emakeWith(HasCap::class, ['params' =\u003e $params]);\n});\n```\n\n### 'codezone/router/conditions/factories' filter\n\nAs an alternative to using the filter above, you may also implement the `Factory` interface to register a\ncondition factory.\n\n```php\nadd_filter(Router::class . '\\\\' . 'conditions_factory', function(Condition|null $instanceOrNull, array $attributes = []) {\n    //Check if this is our named condition\n    if ($name !== 'can') {\n        return $instanceOrNull;\n    }\n    \n    $className = $attributes['className'] ?? null;\n    $name = $attributes['name'] ?? null;\n    $signature = $attributes['signature'] ?? null;\n    \n    //The signature is the part of the route name after the \":\". We need to break it into an array.\n    $params = explode(',', $signature);\n    \n    return container-\u003emakeWith(HasCap::class, ['params' =\u003e $params]);\n});\n```\n\n### 'codezone/router/middleware/factory' filter\n\nA filter for manually handling the instantiation of named middleware. Use this filter if you need to pass extra\nto parse the middleware signature and pass extra parameters to the middleware constructor.\n\n```php\nadd_filter(Router::class . '\\\\' . 'middleware_factory', function(Middleware|null $instanceOrNull, array $attributes = []) {\n    //Check if this is our named middleware\n    if ($name !== 'can') {\n        return $instanceOrNull;\n    }\n    \n    $className = $attributes['className'] ?? null;\n    $name = $attributes['name'] ?? null;\n    $signature = $attributes['signature'] ?? null;\n    \n    //The signature is the part of the route name after the \":\". We need to break it into an array.\n    $params = explode(',', $signature);\n    \n    return container-\u003emakeWith(UserHasCap::class, ['params' =\u003e $params]);\n});\n```\n\n### 'codezone/router/middleware/factories' filter\n\nAs an alternative to using the filter above, you may also implement the `Factory` interface to register a\nmiddleware factory.\n\n```php\nadd_filter(Router::class . '\\\\' . 'conditions_factories', function($factories) {\n    $factories[UserHasCap::class] = UserHasCapFactory::class;\n    return $factories;\n});\n```\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthecodezone%2Fwp-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthecodezone%2Fwp-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthecodezone%2Fwp-router/lists"}