当前位置:网站首页>Codeignier framework implements restful API interface programming
Codeignier framework implements restful API interface programming
2022-07-28 19:43:00 【wyqgg123】
summary
The company interface code uses CodeIgnier frame , So I use CodeIgnier The framework implements a simple restful Style interface .
CodeIgnier The framework has no resource routing by default , Only used in routing HTTP Verbs are as follows :

In the realization of restful When programming the style interface, you need to define the parameters and types of the route. The specific code is as follows :
route routes.php Code
// Default controller
$route['default_controller'] = 'welcome';
// Error page
$route['404_override'] = '';
// This option can automatically URL Hyphens in controllers and methods in ('-') Convert to underline ('_')
$route['translate_uri_dashes'] = FALSE;
/* * restful Interface programming */
// The page display get request
$route['api']['get'] = 'api/index';
// Display a piece of data get request
$route['api/(:num)']['GET'] = 'api/view/$1';
// Add a piece of data post request
$route['api']['POST'] = 'api/add';
// Modify a piece of data post request
$route['api/(:num)']['POST'] = 'api/edit/$1';
// Modify the data page display put request
$route['api/(:num)']['PUT'] = 'api/edit/$1';
// Delete a piece of data delete request
$route['api/(:num)']['DELETE'] = 'api/delete/$1';
Here I think it inconvenient to write so many routes every time , So I wrote a function to generate these routes , It only needs to be called once , The code is as follows :
/* * restful Interface programming * params route array Route array * params name string restful Routing name */
function restful(&$route,$name){
// The page display get request
$route[$name]['get'] = $name.'/index';
// Display a piece of data get request
$route[$name.'/(:num)']['GET'] = $name.'/view/$1';
// Add a piece of data post request
$route[$name]['POST'] = $name.'/add';
// Modify a piece of data post request
$route[$name.'/(:num)']['POST'] = $name.'/edit/$1';
// Modify the data page display put request
$route[$name.'/(:num)']['PUT'] = $name.'/edit/$1';
// Delete a piece of data delete request
$route[$name.'/(:num)']['DELETE'] = $name.'/delete/$1';
}
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
// Call function generation restful route
restful($route,'api');
Below I write an example to implement a simple increment 、 Delete 、 Change 、 check
controller Api Code :
<?php
/** * Created by PhpStorm. * User: wyq * Date: 2021/8/3 * Time: 16:00 */
class Api extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('admins_model');
// Load helper functions, that is, public functions
$this->load->helper('common_helper');
}
/* * Get all the data get request */
public function index(){
$data = $this->admins_model->findAll();
// Methods in public functions
success($data);
}
/* * Get individual data get request */
public function view($id){
$data = $this->admins_model->findOne($id);
success($data);
}
/* * Add a piece of data */
public function add(){
$data = $_POST;
$data = $this->admins_model->add($data);
if ($data){
success($data);
}else{
// Methods in public functions
fail($data);
}
}
/* * Modify a piece of data */
public function edit($id){
if ($_POST){
// Modify page logic
$data = $_POST;
$data['id'] = $id;
$res = $this->admins_model->dell($data);
if ($res){
success($res);
}else{
fail($res);
}
}else{
// Modify page tactics PUT request
$data = $this->admins_model->findOne($id);
success($data);
}
}
/* * Delete a piece of data */
public function delete($id){
$res = $this->admins_model->del($id);
success($res);
}
}
Helper functions ( Public function )common_helper.php Code :
<?php
/** * Created by PhpStorm. * User: wyq * Date: 2021/8/3 * Time: 17:02 */
/* * Cryptographic functions */
function encrypt($data)
{
$salt = "123123asdasdasd";
$psw = md5($salt . md5($data));
return $psw;
}
/* * General response * @params int code Response code * @params string $msg Response description * @params string $data The response data */
function response($code = 200 , $msg="success" , $data=array()){
$res = array('code'=>$code,'msg'=>$msg,'data'=>$data);
echo json_encode($res);die;
}
/* * Successful response * @params string $msg Response description * @params string $data The response data */
function success($data=array(),$msg="success",$code = 200){
response($code,$msg,$data);
}
/* * Failure response * @params string $msg Response description * @params string $data The response data */
function fail($code = 500 ,$msg="fail"){
response($code,$msg);
}
Model Admins_model Code :
<?php
/** * Created by PhpStorm. * User: wyq * Date: 2021/7/16 * Time: 10:26 */
class Admins_model extends CI_Model
{
public function __construct()
{
parent::__construct();
// Load database
$this->load->database();
}
/* * Get all the data */
public function findAll()
{
$query = $this->db->get('admins');
return $query->result_array();
}
/* * Get a piece of data */
public function findOne($id)
{
$this->db->where('id', $id);
$this->db->select('*');
$query = $this->db->get('admins');
return $query->result();
}
/* * Add a piece of data */
public function add($data){
$res = $this->db->insert('admins',$data);
return $res;
}
/* * Modify a piece of data */
public function dell($data){
$this->db->where('id',$data['id']);
return $this->db->update("admins",$data);
}
/* * Delete a piece of data */
public function del($id){
$this->db->where('id',$id);
return $this->db->delete('admins');
}
}
Here is the most basic restful Interface routing , And the realization of the controller model , Here I use postman Test whether the interface is successfully implemented , Here I only show one deletion message .
Before operation :

After the operation :

Interface returns data :

边栏推荐
- Rust 入门指南(modules 和工程结构)
- How does app automated testing achieve H5 testing
- Nips18 (AD) - unsupervised anomaly detection using geometric transformations using geometric augmentation
- 宝塔面板搭建小说CMS管理系统源码实测 - ThinkPHP6.0
- BeanFactory not initialized or already closed - call ‘refresh‘ before accessing beans via the Applic
- 可转债概念表 x Notion 给你方便快捷的体验!
- 读了三年论文,我今天才学会阅读摘要
- WPF 实现带蒙版的 MessageBox 消息提示框
- Saltstack configuration management
- 亚马逊推出Amazon One手掌支付系统,非接触式掌静脉识别市场有望爆发
猜你喜欢

基于C语言的信息管理系统和小游戏

Thoroughly understand bit operations - shift left, shift right

你知道雨的类型有几种?

NetCoreAPI操作Excel表格

BLDC 6-step commutation simulink

CodeIgnier框架实现restful API接口编程

英文翻译西班牙语-批量英文翻译西班牙工具免费

企业级分布式爬虫框架入门

Using Baidu easydl to realize chef hat recognition of bright kitchen and stove

Basic concept and essence of Architecture
随机推荐
助力面板行业创新,FPGA将成屏厂TCON最佳选择?
SaltStack配置管理
In order to develop high-end photoresist, Jingrui Co., Ltd. invested 75million yuan to purchase SK Hynix ASML lithography machine
Report redirect after authorized login on wechat official account_ The problem of wrong URI parameters
博途1200/1500PLC上升沿下降沿指令编程应用技巧(bool数组)
英文翻译葡萄牙语-批量英文转换葡萄牙语-各种语言免费互译转换
App自动化测试是怎么实现H5测试的
NetCoreAPI操作Excel表格
Android-第十三节03xUtils-数据库框架(增删改查)详解
Cell综述:人类微生物组研究中的单细胞方法
Taking the opportunity of digital transformation, how can 3C enterprises achieve efficient collaboration through SRM supplier cloud collaboration platform?
Force buckle 1331. Array serial number conversion
时间转日期的sql语句应该怎么写?
First blog
Pytoch: implementation of crossentropyloss and labelsmoothing
以数字化转型为契机,3C企业如何通过SRM供应商云协同平台实现高效协同?
宝塔面板搭建小说CMS管理系统源码实测 - ThinkPHP6.0
Rust Getting Started Guide (rustup, cargo)
个人博克系统登录点击图形验证码的集成与实现
软考高级考试中有五大证书,哪个更值得考?