PHP技术交流程序员

CI(CodeIgniter )封装自定义Restful控制器

2017-12-14  本文已影响326人  IT锟

RestfulApi的官方定义这里不再赘述,我个人给他定义就是,把一个表的增删改查接口封装起来,提供统一的接口给调用者。

如果是写API接口,表的增删改查何其之多,基本也都一样,我一开始也是每个表的模型里面都去写增删改查,后来写多了就想偷懒了。于是便有了下面的这个封装,只是个人的一个思路,不一定完美,欢迎大家指正。

模型(model)

首先是模型先上代码:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class MY_model extends CI_Model{

    //表名
    public $TAB_NAME;
    //主键
    public $key = "id";

    //操作规则
    /**

    [
        "caid"=>[
            "type"=>"int",
            "AddAllowNull"=>true,
            "editAllowNull"=>false
        ],
        "name"=>[
            "type"=>"string",
            "AddAllowNull"=>false,
            "editAllowNull"=>false
        ]
    ]

     */
    public $modelRule = [];

    public function __construct(){
        parent::__construct();

    }

    //所有商品列表
    public function all($offset = 0,$limit = 0){
        return $this->db->get($this->TAB_NAME,$limit,$offset)->result_array();
    }

    //查询
    public function select($where = [],$offset = 0,$limit = 0){
        return $this->db->get_where($this->TAB_NAME, $where, $limit, $offset)->result_array();
    }

    //全部数量
    public function count(){
        $this->db->select('count(*) count');
        return $this->db->get($this->TAB_NAME)->row_array();
    }

    //添加
    public function add($data){
        $this->db->insert($this->TAB_NAME,$data);
        return $this->db->insert_id();
    }

    //编辑
    public function edit($idName,$id,$date){
        $condition[$idName] = $id;
        $this->db->where($condition)->update($this->TAB_NAME,$date);
        return $this->db->affected_rows();
    }

    //删除
    public function del($idName,$id){
        $condition[$idName] = $id;
        $this->db->where($condition)->delete($this->TAB_NAME);
        return $this->db->affected_rows();
    }

}

这里面封装了增删改查和总数量的方法。表名(TAB_NAME)和主键(key)由继承者提供,这个不需要多做说明。

这里需要说明的是modelRule,这样封装我想了很久作用在于:因为每个表他的字段不一样,每个字段类型也不一样,并且是否修改时允许为空也不一样,于是便想到用数组来做配置,如果看不太懂,可以看完下面的控制器结合着看或许就明白了。

控制器(Controller)

控制器是提供给外面调用的入口,依次去调用模型里面的方法就好。

//Restful控制器
class RestfulController extends CI_Controller{

    //数据库model
    protected $model;

    //列表
    public function all(){
        $list = $this->model->all();
        rJson($list);
    }

    //添加
    public function add(){
        //临时数组
        $data = [];
        foreach ($this->model->modelRule as $key=>$value){
            $inputValue = $this->input->post($key);
            $rul = $this->model->modelRule[$key];
            //判断是否允许为空
            if ($inputValue == null) {
                if (!$rul['AddAllowNull']) {
                    rParameterError();
                }
            }
            $data[$key] = $inputValue;
        }
        $r = $this->model->add($data);
        if ($r>0){
            rJson($r,"添加成功",true);
        }else{
            rJson(null,"添加失败",false);
        }
    }

    //编辑
    public function edit(){

        //临时数组
        $data = [];
        $mKey = $this->input->post($this->model->key);
        if ($mKey == null){
            rParameterError();
        }
        foreach ($this->model->modelRule as $key=>$value){
            $inputValue = $this->input->post($key);
            $rul = $this->model->modelRule[$key];
            //判断是否允许为空
            if ($inputValue == null) {
                if (!$rul['editAllowNull']) {
                    rParameterError();
                }
            }
            $data[$key] = $inputValue;
        }

        $r = $this->model->edit($this->model->key,$mKey,$data);
        if ($r>0){
            rJson(null,"修改成功",true);
        }else{
            rJson(null,"修改失败",false);
        }

    }

    //删除
    public function del()
    {

        $mKey = $this->input->post($this->model->key);
        if ($mKey == null) {
            rParameterError();
        }
        $r = $this->model->del($this->model->key,$mKey);
        if ($r>0){
            rJson(null,"删除成功",true);
        }else{
            rJson(null,"删除失败",false);
        }

    }

}

到这里两个基类就写完了。

子模型继承

这里我以分类表为例吧,直接上代码

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Category_model extends MY_model
{
    public function __construct()
    {
        parent::__construct();
        //表名
        $this->TAB_NAME = "category";
        //主键
        $this->key = "caid";
        //字段操作类型 可以扩展
        $this->modelRule = [
            "caid"=>[
                //数据类型,左右可以做安全过滤,我的范例里面没做
                "type"=>"int",
                //调用添加接口是否为空
                "AddAllowNull"=>true,
                 //调用编辑接口是否为空
                "editAllowNull"=>false
            ],
            "name"=>[
                "type"=>"string",
                "AddAllowNull"=>false,
                "editAllowNull"=>false
            ]
        ];

    }
}

子控制器继承

控制器的基础就很简单了,什么都不用写,在构造函数里面初始化下model就可以了。

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Category extends RestfulController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model("Category_model");
        $this->model = $this->Category_model;

    }
}

以后再添加表什么的,就不用再每个都去写增删改查了。

[获取授权]

上一篇 下一篇

猜你喜欢

热点阅读