必须引入chriskacerguis/codeigniter-restserver库,配置autoload和路由,控制器继承REST_Controller并按{action}_{verb}命名方法,通过$this->get()/post()/put()获取参数,响应自动适配格式。

要在CodeIgniter框架中快速启用RESTful风格API开发,必须明确CI原生不支持REST,需依赖第三方扩展库实现HTTP动词路由映射、请求解析与响应封装等功能。
引入REST_Controller扩展库
下载chriskacerguis/codeigniter-restserver项目源码,解压后将application/libraries/REST_Controller.php和application/libraries/Format.php复制到CI项目的对应目录下。
确保CodeIgniter版本为3.x(该扩展库不兼容CI4),【CI 4用户需改用codeigniter4/restserver或自建中间件】。
在application/config/autoload.php中添加:$autoload['libraries'] = array('rest');。
配置路由以匹配REST语义
编辑application/config/routes.php,添加资源化路由规则:
$route['api/users'] = 'user/index';
$route['api/users/(:num)'] = 'user/index/$1';
这样GET /api/users会调用User控制器的index_get()方法,GET /api/users/123则调用index_get(123)。
注意:不要写成$route['users'] = 'user',否则无法触发REST_Controller的动词分发机制。
编写符合REST语义的控制器
创建application/controllers/User.php,继承REST_Controller而非CI_Controller:
class User extends REST_Controller { public function index_get($id = NULL) { if ($id === NULL) { $this->response(['users' => $this->get_all_users()], 200); } else { $user = $this->get_user_by_id($id); if ($user) { $this->response($user, 200); } else { $this->response(['error' => 'User not found'], 404); } } } }
方法名必须严格遵循{action}_{http_verb}格式,如login_post、profile_put、avatar_delete——【大小写敏感,拼写错误将导致404】。
POST/PUT/PATCH请求体中的参数通过$this->post()、$this->put()、$this->patch()获取,不能用$this->input->post()。
处理不同请求类型与数据格式
方法一:自动解析Content-Type头
REST_Controller会根据请求头Accept或Content-Type自动选择输入输出格式。发送JSON请求时,务必设置Header:Content-Type: application/json,否则$this->put()返回空数组。
方法二:强制指定输入格式
在控制器构造函数中添加:$this->request->format = 'json';可绕过头检测,适用于调试阶段或前端未正确设头的场景。
方法三:响应多格式支持
调用$this->response($data, 200)时,若客户端Accept头为application/xml,将自动序列化为XML;设为text/html则返回HTML表格——前提是Format.php已加载且对应格式驱动存在。
身份验证与权限控制
第一步:启用Token验证
在REST_Controller构造函数中传入['auth' => 'bearer'],或在config/rest.php中设置$config['rest_auth'] = 'bearer';。
第二步:在请求Header中携带Token
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...
第三步:重写_auth_override_check()方法实现自定义校验逻辑
例如查询数据库验证token有效性,并将用户ID存入$this->rest->user_id供后续操作使用。不重写该方法将直接拒绝所有带token的请求。
注意:Basic Auth需额外配置Apache/Nginx启用Authorization头透传,否则$_SERVER['HTTP_AUTHORIZATION']为空。











