codeigniter restful路由可一键生成:ci3用自定义restful()函数,ci4用$routes->resource(),rest server则依赖方法名后缀自动映射动词。

想让CodeIgniter的RESTful路由配置不重复写一堆相似规则、避免手误漏掉某个HTTP方法、还能快速复用到新资源上,就得绕过手动逐条定义的原始写法。
用restful()函数一键生成标准REST路由
直接在application/config/routes.php末尾添加一个自定义函数,把重复的GET/POST/PUT/DELETE模板封装起来。
在文件最底部(【必须放在所有$route赋值之后】)粘贴以下代码:
function restful(&$route, $name) {<br> $route[$name]['get'] = $name . '/index';<br> $route[$name . '/(:num)']['GET'] = $name . '/view/$1';<br> $route[$name]['POST'] = $name . '/add';<br> $route[$name . '/(:num)']['POST'] = $name . '/edit/$1';<br> $route[$name . '/(:num)']['PUT'] = $name . '/edit/$1';<br> $route[$name . '/(:num)']['DELETE'] = $name . '/delete/$1';<br>}
调用它只需一行:restful($route, 'users');,就会自动注册/users和/users/123对应的所有标准动词路由。
这个函数不依赖任何第三方库,纯原生PHP,CI3全版本兼容。注意:$name参数不能带前缀斜杠,比如写'api/users'会生成错误路径,应写'api/users'以外的纯资源名。
启用REST Server后改用HTTP动词映射语法
先通过Composer安装chriskacerguis/codeigniter-restserver:composer require chriskacerguis/codeigniter-restserver。
复制vendor/chriskacerguis/codeigniter-restserver/src/rest.php到application/config/rest.php。
当代理已经知道网站路由或内容URL,并且在启动前需要有效的sitemap XML、sitemap索引或robots.txt引用时,请使用sitemap。这是一个发布构件技能,而不是爬虫或SEO平台。
创建控制器继承RestController,例如application/controllers/Api/Users.php:
class Users extends RestController {<br> public function index_get() { /* GET /api/users */ }<br> public function view_get($id) { /* GET /api/users/123 */ }<br> public function add_post() { /* POST /api/users */ }<br> public function edit_put($id) { /* PUT /api/users/123 */ }<br> public function edit_post($id) { /* POST /api/users/123 —— 有些前端只支持POST模拟PUT */ }<br> public function delete_delete($id) { /* DELETE /api/users/123 */ }<br>}
此时routes.php里只需写一条路由:$route['api/users']['GET'] = 'api/users/index';,其余动词由RestController自动识别方法名后缀,无需再在routes.php里穷举。
【控制器方法名必须严格按_xxx动词格式命名,否则404】,比如写成indexGet()或get_index()都不生效。
CI4中用resource()快捷注册(仅限CodeIgniter 4)
如果你用的是CI4,routes.php已改为app/Config/Routes.php,里面直接调用$routes->resource('users');即可。
这条语句会自动生成全部7个标准REST动作路由,包括:
GET /users → Users::index
GET /users/new → Users::new
GET /users/123 → Users::show
GET /users/123/edit → Users::edit
POST /users → Users::create
PUT /users/123 → Users::update
DELETE /users/123 → Users::delete
不需要写任何回调字符串,也不用拼接$1占位符——CI4自动完成参数注入和方法绑定。
若要加API前缀,写成$routes->resource('users', ['path' => 'api']);,生成的路径就是/api/users。










