{"id":18750645,"url":"https://github.com/webiny/router","last_synced_at":"2025-08-24T18:41:59.422Z","repository":{"id":20228443,"uuid":"23500299","full_name":"webiny/Router","owner":"webiny","description":"[READ-ONLY]  PHP router component is used for mapping defined paths/urls to appropriate controllers or services. (master at Webiny/Framework)","archived":false,"fork":false,"pushed_at":"2017-11-26T21:25:16.000Z","size":34,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":13,"default_branch":"master","last_synced_at":"2024-12-28T22:53:14.809Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://www.webiny.com/","language":"PHP","has_issues":false,"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/webiny.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}},"created_at":"2014-08-30T20:39:14.000Z","updated_at":"2023-05-21T17:38:08.000Z","dependencies_parsed_at":"2022-07-27T01:02:20.305Z","dependency_job_id":null,"html_url":"https://github.com/webiny/Router","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webiny%2FRouter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webiny%2FRouter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webiny%2FRouter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webiny%2FRouter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/webiny","download_url":"https://codeload.github.com/webiny/Router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239635835,"owners_count":19672238,"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-11-07T17:12:41.309Z","updated_at":"2025-02-19T10:22:29.124Z","avatar_url":"https://github.com/webiny.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"Router Component\n================\n\nRouter component is used for mapping defined paths/urls to appropriate controllers or services.\n\nInstall the component\n---------------------\nThe best way to install the component is using Composer.\n\n```bash\ncomposer require webiny/router\n```\nFor additional versions of the package, visit the [Packagist page](https://packagist.org/packages/webiny/router).\n\n## Usage\n\nDefining a route is a rather easy process, you set a route name and underneath you define the path and the callback.\nHere is an example:\n\n```yaml\n    Router:\n        Routes:\n            BlogTag:\n                Path: blog/tag/{tag}\n                Callback: MyApp\\Blog\\showTag\n            BlogComments:\n                Path: blog/post/{id}/comments\n                Callback:\n                    Class: MyApp\\Blog\n                    Method: showComments\n            BlogPost:\n                Path: blog/post/{slug}/{id}\n                Callback: MyApp\\Blog\\showPost\n                Options:\n                    slug:\n                        Pattern: .*?\n            BlogAuthor:\n                Path: blog/authors/{author}\n                Callback: MyApp\\Blog\\showAuthorPosts\n                Options:\n                    author:\n                        Default: webiny\n            Blog:\n                Path: blog\n                Callback: MyApp\\Blog\\index\n```\n\nIf a route is matched you will get an instance of `MatchedRoute`. The `getCallback` method returns the value of callback\nparameter of the matched route. The second method `getParams` returns the values of the parameters defined in the `Path` section.\n\nBy registering a default `Router` configuration, `Router` will automatically set the defined routes and cache driver.\n```php\n    Router::setConfig($pathToYourConfig);\n```\n\nLater on you can use the `RouterTrait` access that `Router` instance.\n\n**NOTICE:**\nWhen defining the routes in your config file, make sure that you put routes with lesser precision to the bottom, and\nroutes with a more stricter rules at the top. A common pitfall is that a route with more wider pattern is matched before\na route with a more stricter rules due to the fact that the `Router` loops over the defined routes in the same order\nthat they are defined inside the config file, and it stops once the first route is matched.\n\n### `Options`\n\nThe `Options` attribute under the route provides you two additional options that you can set under each route.\n\n#### `Pattern`\n\nThe default regex pattern for matching a variable is `{[\\w-]+}`. Using the `Pattern` attribute you can set your own rule.\n\n#### `Default`\n\nThe `Default` attribute gives you the option to set the the default value for a variable.\n\nIf the route is not matched using the current available properties from the url path, `Router` will replace all the\n variable patterns with the default values and try to match the route again.\n\n## Matching routes\n\nTo check if a route matches the given path, use the `RouterTrait` and then just call `$this-\u003erouter()-\u003ematch()` method.\nThe `match` method takes either a string that is representing a url or it can take an instance of `Url` standard object.\nIf the router successfully matches one of the routes it will return an array with callback and params attributes.\nIf the router doesn't match any of the routes, it will return false.\n\n```php\nclass MyClass\n{\n\tuse \\Webiny\\Component\\Router\\RouterTrait;\n\n\tfunction __construct(){\n\t\t$result = $this-\u003erouter()-\u003ematch('blog/tag/some_tag');\n\t\t$result = $this-\u003erouter()-\u003ematch('http://www.webiny.com/blog/post/some-post/12');\n\t}\n}\n```\n\n**NOTE:** `Router` component always returns the **first route** that matches the given path.\n\n## Executing route callback\n\nIf you define your callback as string, you will have to parse and execute it on your own. But if you follow the standard\nstructure of your callback you will be able to use router's `execute` method and pass your `MatchedRoute` to it.\nRouter will then execute the callback for you and do all the checks regarding class and method existence:\n\n```yaml\nBlogComments:\n    Path: blog/post/{id}/comments\n    Callback:\n        Class: MyApp\\Blog\n        Method: showComments\n```\n\n```php\nclass MyClass\n{\n\tuse \\Webiny\\Component\\Router\\RouterTrait;\n\n\tfunction __construct(){\n\t\t$result = $this-\u003erouter()-\u003ematch('blog/post/12/comments');\n\t\tif($result){\n\t\t    $callbackResult = $this-\u003erouter()-\u003eexecute($result);\n\t\t}\n\t}\n}\n```\n\nIf for some reason you need to call the method statically, define your route callback like this:\n\n```yaml\nBlogComments:\n    Path: blog/post/{id}/comments\n    Callback:\n        Class: MyApp\\Blog\n        Method: showComments\n        Static: true\n```\n\n## Generating routes\n\nWith the `Router` your don't have write the urls inside your code or views, instead you can generate the urls from the\ngiven route like this:\n\n```php\nclass MyClass\n{\n\tuse \\Webiny\\Component\\Router\\RouterTrait;\n\n\tfunction __construct(){\n\t\t$url = $this-\u003erouter()-\u003egenerate('BlogTag',  ['tag'=\u003e'html5', 'page'=\u003e1]);\n\t\t// http://www.webiny.com/blog/tag/html5/?page=1\n\t\t// page was not defined in the route, that's why it's appended as a query param\n\n\t\t$url = $this-\u003erouter()-\u003egenerate('BlogAuthor');\n\t\t// http://www.webiny.com/blog/authors/webiny\n\t\t// the value of \"author\" was not set, so the generator used the default value\n\t}\n}\n```\n\nYou see that `Router` replaced the `{tag}` parameter with the provided value, in this case it was `html5`. You can also\nnotice that the `page` parameter isn't defined in our route, so the `Router` appended that parameter as a query string.\n\n## Configuration\n\nThe `Router` component takes one additional configuration parameter, and that is the `Cache` parameter. If either defines\nthe name of the cache service that will be used to cache some of the internal mechanisms, or you can set it to `false` if\nyou don't want the component to use cache.\n\n```yaml\nRouter:\n    Cache: TestCache\n```\n\nUsing the cache can speed up matching of routes, especially more complex ones.\n\nResources\n---------\n\nTo run unit tests, you need to use the following command:\n\n    $ cd path/to/Webiny/Component/Router/\n    $ composer.phar install\n    $ phpunit","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebiny%2Frouter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwebiny%2Frouter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebiny%2Frouter/lists"}