{"id":14987374,"url":"https://github.com/monkenwu/codeigniter4-route-attributes","last_synced_at":"2025-06-17T12:33:55.536Z","repository":{"id":45092596,"uuid":"445772366","full_name":"monkenWu/CodeIgniter4-Route-Attributes","owner":"monkenWu","description":"You can use this library to make CodeIgniter4 able to define routing settings of controllers through comments.","archived":false,"fork":false,"pushed_at":"2022-02-12T15:51:15.000Z","size":179,"stargazers_count":8,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-19T00:12:22.629Z","etag":null,"topics":["attributes","codeigniter4","composer-library","php8","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/monkenWu.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}},"created_at":"2022-01-08T09:07:17.000Z","updated_at":"2024-06-12T08:27:26.000Z","dependencies_parsed_at":"2022-09-15T22:13:04.676Z","dependency_job_id":null,"html_url":"https://github.com/monkenWu/CodeIgniter4-Route-Attributes","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/monkenWu/CodeIgniter4-Route-Attributes","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monkenWu%2FCodeIgniter4-Route-Attributes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monkenWu%2FCodeIgniter4-Route-Attributes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monkenWu%2FCodeIgniter4-Route-Attributes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monkenWu%2FCodeIgniter4-Route-Attributes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/monkenWu","download_url":"https://codeload.github.com/monkenWu/CodeIgniter4-Route-Attributes/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monkenWu%2FCodeIgniter4-Route-Attributes/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260358776,"owners_count":22997117,"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":["attributes","codeigniter4","composer-library","php8","router"],"created_at":"2024-09-24T14:14:31.440Z","updated_at":"2025-06-17T12:33:50.524Z","avatar_url":"https://github.com/monkenWu.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CodeIgniter4-Route-Attribute\n\n[![Latest Stable Version](http://poser.pugx.org/monken/ci4-route-attributes/v)](https://packagist.org/packages/monken/ci4-route-attributes) [![Total Downloads](http://poser.pugx.org/monken/ci4-route-attributes/downloads)](https://packagist.org/packages/monken/ci4-route-attributes) [![Latest Unstable Version](http://poser.pugx.org/monken/ci4-route-attributes/v/unstable)](https://packagist.org/packages/monken/ci4-route-attributes) [![License](http://poser.pugx.org/monken/ci4-route-attributes/license)](https://packagist.org/packages/monken/ci4-route-attributes) [![PHP Version Require](http://poser.pugx.org/monken/ci4-route-attributes/require/php)](https://packagist.org/packages/monken/ci4-route-attributes)\n\nYou can use this library to make CodeIgniter4 able to define routing settings of controllers through comments.\n\n[中文手冊](README_zh-TW.md)\n\n\u003c!-- TOC --\u003e\n\n- [CodeIgniter4-Route-Attribute](#codeigniter4-route-attribute)\n    - [Quick demo](#quick-demo)\n    - [Installation Guide](#installation-guide)\n        - [Requirements](#requirements)\n        - [Composer Install](#composer-install)\n    - [Instructions](#instructions)\n        - [Production and Development Environment](#production-and-development-environment)\n            - [Configuration File](#configuration-file)\n            - [Generate Route Attribute Definition File](#generate-route-attribute-definition-file)\n            - [Update Route Attribute Definition File](#update-route-attribute-definition-file)\n        - [Route](#route)\n            - [options](#options)\n            - [ignoreGroup](#ignoregroup)\n            - [Placeholder](#placeholder)\n            - [Single Method to declare multiple Routes](#single-method-to-declare-multiple-routes)\n        - [RouteRESTful](#routerestful)\n            - [Resource Route](#resource-route)\n            - [Presenter Route](#presenter-route)\n            - [websafe](#websafe)\n            - [only](#only)\n            - [except](#except)\n            - [placeholder](#placeholder)\n            - [options](#options-1)\n            - [ignoreGroup](#ignoregroup-1)\n        - [RouteGroup](#routegroup)\n        - [RouteEnvironment](#routeenvironment)\n\n\u003c!-- /TOC --\u003e\n\n## Quick demo \n\n```php\nnamespace App\\Controllers;\n\nuse monken\\Ci4RouteAttributes\\Route;\n\nclass Ci4Controller extends BaseController\n{\n    #[Route(path: 'attr/route', methods: [\"get\"])]\n    public function hello()\n    {\n        return \"PHP8Attributes\";\n    }\n}\n\n```\n\nUse the definition of `#[Route(path: 'attr/route', methods: [\"get\"])]`, means the same settings were done in your routing configuration:\n\n```php\n$routes-\u003eget('attr/route', 'App\\Controllers\\Ci4Controller::hello');\n```\n\nThis library will smartly connect your controller and routing automatically, which means you can access to the `hello` method in `Ci4Controller` through the path of `/attr/route`.\n\n## Installation Guide\n\n### Requirements\n\n1. CodeIgniter Framework 4\n2. Composer\n3. PHP8↑\n\n### Composer Install\n\nUse Composer to download the library needed dependency under the project root.\n\n```\ncomposer require monken/ci4-route-attributes\n```\n\nUse the library built-in command to initialize the needed files.\n\n```\nphp spark route-attr:init\n```\n\nThe upper command will make to changes on our project.\n\n1. `app/Config` will have a `RouteAttributes.php` configuration file, you can adjust the library's execution setting through this file. And it looks like this:\n    ```php\n    \u003c?php\n\n    namespace Config;\n\n    use CodeIgniter\\Config\\BaseConfig;\n\n    class RouteAttributes extends BaseConfig\n    {\n\n        /**\n        * Routes are automatically registered only if this is set to `true`\n        *\n        * @var boolean\n        */\n        public bool $enabled = true;\n\n        /** \n        * autoscan namespaces\n        *\n        * @var array\u003cstring\u003e\n        */\n        public array $controllerNamespaces = [\n            \"App\\Controllers\"\n        ];\n\n        /**\n        * Generate production environment route definition file path\n        *\n        * @var string\n        */\n        public string $routeDefinitionFilePath = WRITEPATH . 'cache';\n\n        /**\n        * Whether to use pre-generated route definition files in production.\n        * Note that when this option is set to `true`, controller files will not be automatically\n        * scanned in production environment. You must use `route-attr:make` command to generate\n        * route definition files to improve performance in production environment.\n        *\n        * @var boolean\n        */\n        public bool $productionUseDefinitionFile = true;\n    }\n    ```\n2. Automatically write the library needed events into the endpoint of file `app/Config/Events.php`, the event will be used when CodeIgniter4 initializes, automatically registering routes. The command will write the contents in as below:\n    ```php\n    Events::on('pre_system', function(){\n        \\monken\\Ci4RouteAttributes\\RouteAttributes::runHandler();\n    });\n    ```\n\n## Instructions\n\nIn short, this library is a [CodeIgniter4 Router](https://codeigniter.com/user_guide/incoming/routing.html) presentative way under the PHP8 Attributes feature, it merely provides litte mapping and encapsulation for some CodeIgniter4 Router methods. Other than that, there's no other extra functionalities.\n\nBy means of scanning the comments automatically inside the Controller, routes and methods will be connected, enables you to write routing rules straightforwardly, and maintain the relationship between Controllers and Routes in a convenient way.\n\n### Production and Development Environment\n\nWhen you are using this library in Development environment under CodeIgnitere4 framework, it will re-analyze all Controllers classes everytime when a request should occur, and meanwhile handle with the correspond Route Attribures. This strategy can bring maximum convenience to developing, changes of Route Attributes will take effect immediately. However, in production environment, this strategy will cause considerale performance loss. Therefore our library provides a cache-like method to lower the performance loss aiming at production environment.\n\n#### Configuration File\n\nYou can find the two adjustable variables, `routeDefinitionFilePath` and `productionUseDefinitionFile`, in `app/Config/RouteAttributes.php`.\n\nYou can use `routeDefinitionFilePath` to define storage location of your configuration file for production environment, it will be placed at `project_root/writable/cache` as default.\n\nYou can change `productionUseDefinitionFile` as `true` or `false` to define whether to activate Route Attributes definition file in production environment or not to achieve the best performance. If it's `false`, then on every request of production environment, they will be re-scanned and Route Attributes inside Controllers will be handled.\n\n#### Generate Route Attribute Definition File\n\nYou can generate your Route Attribute Definition File using the command below, to lower the performance loss: \n\n```\nphp spark route-attr:make\n```\n\nUpper mentioned command will generate a `RouteAttributesDefinition` file under the path defined in `routeDefinitionFilePath`.\n\n#### Update Route Attribute Definition File\n\nThere are two ways to update the Route Attributes Definition File for your Production environment\n\n1. Run `php spark route-attr:make` again, new contents will directly cover the old ones.\n2. Delete `RouteAttributesDefinition` file, if the library couldn't find the file, it will scan and generate a Route Attribute Definition File automatically.\n\n### Route\n\nYou can register your routes like this:\n\n```php\nnamespace App\\Controllers;\n\nuse monken\\Ci4RouteAttributes\\Route;\n\nclass Ci4Controller extends BaseController\n{\n    #[Route(path: 'attr/route', methods: [\"get\"])]\n    public function hello()\n    {\n        return \"PHP8Attributes\";\n    }\n}\n```\n\nIn this example, `Path` represents the acutal path to call this Controller method, and `method` will expect you to pass a String array, including the HTTP verbs to access to this Controller method.\n\nAccording to the [Router Global Options](https://codeigniter.com/user_guide/incoming/routing.html#global-options) of the CodeIgniter4, you can use the following verbs: `add`, `get`, `post`, `put`, `head`, `options`, `delete`, `path`, and `cli`.\nYou can declare several verbs to achieve the effect of switching between different `method` under the same `path` with access to the identical Controller effects.\n\n#### options\n\nYou can pass in options array to make special adjustments to routes, the library won't do any processing or judging to your options, this means you must consult the CodeIgniter4 documentation to write the correct options. Usually, this parameter will be like this:\n\n```php\n#[Route(path: 'attr/route', methods: [\"get\"], options:[\n    'filter' =\u003e 'auth',\n    'hostname' =\u003e 'accounts.example.com'\n])]\n```\n\n#### ignoreGroup\n\nIf you are using `RouteGroup` to configure routes under the same controller uniformly, but wanting to set one of them apart without extending `RouteGroup`. You can set this parameter to `true`, making routing an independent job like this:\n\n```php=\n#[Route(path: 'attr/route', methods: [\"get\"], ignoreGroup: true)]\n```\n\n#### Placeholder\n\nYou only need to concentrate on the placeholder configuration in your `path`, the library will determine the parameter amount of your controller and finish the correct route settings.\n\n```php\n\u003c?php\n\nnamespace App\\Controllers;\n\nuse monken\\Ci4RouteAttributes\\Route;\n\nclass Ci4Controller extends BaseController\n{\n    #[Route(path: 'test/(:segment)/(:segment)/(:segment)', methods: [\"get\"])]\n    public function hello($a, $b, $c)\n    {\n        echo $a . '\u003cbr\u003e';\n        echo $b . '\u003cbr\u003e';\n        echo $c . '\u003cbr\u003e';\n    }\n\n}\n```\n\nEquals to:\n\n```php\n$route-\u003eget('test/(:segment)/(:segment)/(:segment)', 'App\\Controllers\\Ci4Controller::hello/$1/$2/$3');\n```\n\n#### Single Method to declare multiple Routes\n\n\nIf you need, you can also tie several route settings to a single Method.\n\n```php\nnamespace App\\Controllers;\n\nuse monken\\Ci4RouteAttributes\\Route;\n\nclass Ci4Controller extends BaseController\n{\n    #[Route(path: 'attr/route', methods: [\"get\"])]\n    #[Route(path: 'hello/msg', methods: [\"get\"])]\n    public function hello()\n    {\n        return \"PHP8Attributes\";\n    }\n}\n```\n\nThrough the upper settings, no matter accessing to `attr/route` or `hello/msg`, they are all pointing at the same Ci4Controller's hello method.\n\n### RouteRESTful\n\nCodeIgniter4 offers convenient [RESTful patterns](https://codeigniter.com/user_guide/incoming/restful.html) for you to inherit related class to quickly achieve RESTful design pattern. \nThis library also provides related patterns for you to transform your controller into RESTful routes rapidly.\n\n#### Resource Route\n\n```php\n\u003c?php\n\nnamespace App\\Controllers;\n\nuse CodeIgniter\\RESTful\\ResourceController;\nuse monken\\Ci4RouteAttributes\\RouteRESTful;\n\n#[RouteRESTful(name: 'api/user', type: 'resource')]\nclass UserApi extends ResourceController\n{\n    //...\n}\n```\n\nEquals to:\n\n```php\n$routes-\u003eresource('api/user', [\n    \"controller\" =\u003e 'App\\Controllers\\UserApi'\n]);\n```\n\n`name` means the resource name, can also be declared as a path.\nThere are two available options on `type`, naming `resource` and `presenter`.\n\n#### Presenter Route\n\nYou can adjust the value of `type` to switch RouteRESTful into Presenter Route pattern.\n\n```php\n\u003c?php\n\nnamespace App\\Controllers;\n\nuse CodeIgniter\\RESTful\\ResourcePresenter;\nuse monken\\Ci4RouteAttributes\\RouteRESTful;\n\n#[RouteRESTful(name: 'user', type: 'presenter')]\nclass User extends ResourcePresenter\n{\n    //...\n}\n```\n\n\nEquals to:\n\n```php\n$routes-\u003epresenter('user', [\n    \"controller\" =\u003e 'App\\Controllers\\User'\n]);\n```\n\nYou can adjust RouteRESTful `type` base on your need, through setting up your [ResourceRoute](https://codeigniter.com/user_guide/incoming/restful.html#resource-routes) or [PresenterRoute](https://codeigniter.com/user_guide/incoming/restful.html#presenter-routes).\n\n#### websafe\n\nThis option will be activated only when `type` adopts `resource`. It will add `websafe =\u003e1` into the route's `options` to make it available for HTML forms.\n\n```php\n#[RouteRESTful(name: 'api/user', websafe: true)]\n```\n\n#### only\n\nYou can use `only` option to restrict only generate the route you've mentioned. This parameter only accept one array, composed of method names.\n\n```php\n#[RouteRESTful(name: 'api/user', only: [\n    'index', 'show'\n])]\n```\n\nFor acceptable method names, please refer to our [documentation](https://codeigniter.com/user_guide/incoming/restful.html#limit-the-routes-made).\n\n#### except\n\nYou can use `except` to remove production of some routes, this parameter only accepts one array, composed of method names.\n\n```php\n#[RouteRESTful(name: 'api/user', except: [\n    'new', 'edit'\n])]\n```\n\nFor acceptable method names, please refer to our [documentation](https://codeigniter.com/user_guide/incoming/restful.html#limit-the-routes-made).\n\n#### placeholder\n\nIf your API needs the resource ID, `(:segment)` placeholder will be used as default. But you can also pass `placeholder` parameter to make changes to it:\n\n```php\n#[RouteRESTful(name: 'api/user', placeholder: ':(num)')]\n```\n\n#### options\n\nThrough passing in the options array to do particular revision aiming at the RESTful routes, the library won't do any judgement to your passed options. \n\n\nOne thing should pay extra attention, if parameters like `websafe`, `only`, `except`, or `placeholder` were used, then the library will automatically compose the contents you've passed in with the `options` array. If there's replicated declarations being made, the parameters' content will be focused.\n\nYou must refer to the CodeIgniter4 documentation to write the correct options. Usually, the usage if this parameter will look loke this:\n\n```php\n#[RouteRESTful(name: 'api/user', placeholder: ':(num)', options: [\n    'filter' =\u003e 'auth'\n])]\n```\n\n#### ignoreGroup\n\nIf you are using `RouteGroup` to configure routes under the same controller uniformly, but wanting to set one of them apart without extending `RouteGroup`. You can set this parameter to `true`:\n\n```php\n#[RouteRESTful(name: 'api/user', ignoreGroup: true)]\n```\n\n### RouteGroup\n\nUsually, you will wish not to re-configure the duplicated `path`, such as `/api/v1`. Hence you can make use of `RouteGroup` to uniformly apply the same `path` or `options` to all routing settings under the class.\n\n```php\n\u003c?php\n\nnamespace App\\Controllers;\n\nuse monken\\Ci4RouteAttributes\\Route;\nuse monken\\Ci4RouteAttributes\\RouteGroup;\n\n#[RouteGroup(name: '/route/testgroup', options: ['filter' =\u003e 'auth'])]\nclass Group extends BaseController\n{\n\n    #[Route(path: 'getindex', methods: ['get'])]\n    public function index()\n    {\n        return \"hi\";\n    }\n\n    #[Route(path: 'get/something', methods: ['get'])]\n    public function somefunction()\n    {\n        return \"something\";\n    }\n}\n\n```\n\nUpper settings equals to:\n\n```php\n$routes-\u003egroup(\n    '/route/testgroup',\n    ['filter' =\u003e 'auth'],\n    function ($routes) {\n        $routes-\u003eget('getindex', 'App\\Controllers\\Group ::index');\n        $routes-\u003eget('get/something', 'App\\Controllers\\Group ::somefunction');\n    }\n);\n```\n### RouteEnvironment\n\nYou can create special routes for specified environment, for instance, routes for development will be unavailable in production and staging environment. This requirement can be done through declaring `RouteEnvironment` in your class.\n\n```php\n\u003c?php\n\nnamespace App\\Controllers;\n\nuse monken\\Ci4RouteAttributes\\Route;\n\n#[RouteEnvironment(type: \"development\")]\nclass EnvRoute extends BaseController\n{\n\n    #[Route(path:'dev/tool', methods:['cli'])]\n    public function devToolMethod()\n    {\n        return \"tool msg\";\n    }\n\n    #[Route(path:'dev/page', methods:['get'])]\n    public function devPageMethod()\n    {\n        return \"page msg\";\n    }\n\n```\n\nUpper setting equals to:\n\n```php\n$routes-\u003eenvironment('development', function ($routes) {\n    $routes-\u003ecli('dev/tool', 'App\\Controllers\\EnvRoute::devToolMethod');\n    $routes-\u003eget('dev/page', 'App\\Controllers\\EnvRoute::devPageMethod');\n});\n```\n\nIf you need, `RouteEnvironment` can also work with `RouteGroup`:\n\n```php\n\u003c?php\n\nnamespace App\\Controllers;\n\nuse monken\\Ci4RouteAttributes\\Route;\nuse monken\\Ci4RouteAttributes\\RouteGroup;\n\n#[RouteEnvironment(type: \"development\")]\n#[RouteGroup('/dev')]\nclass EnvRoute extends BaseController\n{\n\n    #[Route(path:'tool', methods:['cli'])]\n    public function devToolMethod()\n    {\n        return \"tool msg\";\n    }\n\n    #[Route(path:'page', methods:['get'])]\n    public function devPageMethod()\n    {\n        return \"page msg\";\n    }\n\n```\n\nUpper setting equals to:\n\n```php\n$routes-\u003eenvironment('development', function ($routes) {\n    $routes-\u003egroup(\n        '/dev',\n        function ($routes) {\n            $routes-\u003ecli('tool', 'App\\Controllers\\EnvRoute::devToolMethod');\n            $routes-\u003eget('page', 'App\\Controllers\\EnvRoute::devPageMethod');\n        }\n    );\n});\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmonkenwu%2Fcodeigniter4-route-attributes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmonkenwu%2Fcodeigniter4-route-attributes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmonkenwu%2Fcodeigniter4-route-attributes/lists"}