当前位置:网站首页>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 :

边栏推荐
- navicate修改数据库名的方式
- leetcode day3 超过经理收入的员工
- How does app automated testing achieve H5 testing
- 峰值速率超2Gbps!高通在中国首发通过5G毫米波MIMO OTA测试
- npm安装和卸载全局包
- Saltstack system initialization
- Pagoda panel construction novel CMS management system source code measurement - thinkphp6.0
- 宝塔面板搭建小说CMS管理系统源码实测 - ThinkPHP6.0
- 云计算笔记part.1——系统管理
- 【微信小程序开发】页面导航与传参
猜你喜欢

SaltStack配置管理

VAE: understanding and implementation of variational self encoder

Iclr21 (classification) - future classic "vit" an image is worth 16x16 words (including code analysis)

Nips18 (AD) - unsupervised anomaly detection using geometric transformations using geometric augmentation

Saltstack system initialization

App自动化测试是怎么实现H5测试的

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

彻底理解位运算——左移、右移

What parameters should be passed in calling integer or character array functions

Convertible bond concept table x notation gives you a convenient and fast experience!
随机推荐
In order to develop high-end photoresist, Jingrui Co., Ltd. invested 75million yuan to purchase SK Hynix ASML lithography machine
The mystery of ID number
2022年全国最新消防设施操作员(中级消防设施操作员)题库及答案
First blog
The United States will provide $25billion in subsidies to encourage chip manufacturers such as Intel to move back to production lines
11. Learn MySQL union operator
Pytoch: implementation of crossentropyloss and labelsmoothing
Force buckle 1331. Array serial number conversion
Getting started with saltstack
Sword finger offer II 109. unlock the password lock
Servlet learning notes
MySQL8 Status Variables: Internal Temporary Tables and Files
Germany and Portugal have announced that they will not disable Huawei 5g equipment, but Germany will set strict restrictions!
VAE: understanding and implementation of variational self encoder
美国将提供250亿美元补贴,鼓励英特尔等芯片制造商迁回产线
Investment of 3.545 billion yuan! Gree Group participates in Xiaomi industry fund
Cvpr19 - adjust reference dry goods bag of tricks for image classification with revolutionary neural network
英文翻译阿拉伯语-批量英文翻译阿拉伯语工具免费
NDK 系列(5):JNI 从入门到实践,爆肝万字详解!
Huawei shares in Nanjing core vision, laying out the solid-state laser radar chip field