CI框架的公共模型类定义与用法

不言
发布: 2018-06-14 11:51:07
原创
2262人浏览过

这篇文章主要介绍了ci框架(codeigniter)公共模型类定义与用法,结合具体实例形式分析了ci框架公共模型类的定义以及基于公共模型类操作数据库的相关实现技巧,需要的朋友可以参考下

本文实例讲述了CI框架(CodeIgniter)公共模型类定义与用法。分享给大家供大家参考,具体如下:

我们都知道,操作数据库的方法都写在模型中。但是一般情况下,一张表往往至少对应4个操作,也就是所谓crud。那么如果20张表,所对应的模型方法,就达到了80个,重复的操作显然这已经是一个体力活儿。

那么就对单表操作时,我们进行一下简单的封装。如下是ci框架的示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

<?php

/**

 * Created by PhpStorm.

 * User: kangjianrong

 * Date: 16-8-26

 * Time: 上午10:29

 */

class My_model extends CI_Model {

  //数据库

  public $errors = array();

  const dataBase = 'qndnew';

  public function __construct()

  {

    // Call the CI_Model constructor

    parent::__construct();

  }

  /**

   * 查询分页数据(使用于简单的单表操作)

   * @param string $model 模型     例如:User_model

   * @param string $table 表名

   * @param string $select_fields 要显示字段

   * @param array $param 查询条件:

   *   compare(比较):

   *     array($key => $val) $key为要操作的字段,$val为要操作的值

   *     array('name !=' => $name, 'id <' => $id, 'date >' => $date);

   *   like(模糊查询)

   *     array('title' => $match, 'page1' => $match, 'page2' => $match)

   *   customStr(自定义字符串):

   *     "name='Joe' AND status='boss' OR status='active'"

   *   in:

   *     array('userName' => array('Frank', 'Todd', 'James'))

   * @param string $page 当前页数(查询全部数据时,设置为空)

   * @param string $limit 查询条数(查询全部数据时,设置为空)

   * @param array $order 排序条件:

   *   array($key => $val)

   *   $key为排序依据的字段,

   *   $val为排序的方式【asc (升序,默认)或 desc(降序), 或 random(随机)】

   * @$isReturnCount boole    是否返回总条数

   * @return array|boolean

   *

   */

  public function pageData($model, $table, $param = array(),$select_fields = '', $page = '1', $limit = '15', $order = array(),$isReturnCount = true){

    if(empty($model) || empty($table)){

      return false;

    }

    $this -> load -> model($model);

    $table = $this->db->dbprefix.$table;

    //处理查询字段

    if(!empty($select_fields)){

      $this->db->select($select_fields)->from($table);

    }elseif(isset($this -> $model -> selectFields)){

      $this->db->select($this -> $model -> selectFields)->from($table);

    }else{

      $this->db->select('*')->from($table);

    }

    //处理查询条件

    if (is_array($param) && count($param) > 0){

      $this -> parseParam($param);

    }

    //统计总数

    if($isReturnCount){

      $rs['count']  = $this->db->count_all_results('',false);//不重置查询构造器

      array_push($this -> errors,$this->db->last_query());

    }

    //分页数据处理

    if(isset($page) && isset($param['limit'])){

      //分页边界值 设置

      $offset = $param['page'] <= 1 ? 0 : ($param['page']-1) * $param['limit'];

      $this->db->limit($param['limit'], $offset);

    }

    //排序规则的组合

    if (!empty($order) && is_array($order))

    {

      foreach ($order as $key => $val)

      {

        $this->db->order_by($key, $val);

      }

    }else{

      //默认按照此表的主键倒序

      $primary = $this->getPrimary();

      if(!empty($primary))

      {

        $this->db->order_by($primary, 'DESC');

      }

    }

    $query = $this->db->get();

    array_push($this -> errors,$this->db->last_query());

    $rs['list'] = $query->result_array();

    return $rs;

  }

  /**

   * 解析参数

   */

  private function parseParam($param){

    if(isset($param['compare'])){

      foreach ($param['compare'] as $key => $val){

        if (!empty($val)) $this->db->where($key, $val);

      }

    }

    if(isset($param['like'])){

      foreach ($param['like'] as $key => $val){

        if (!empty($val)) $this->db->like($key, $val);

      }

    }

    if(isset($param['in'])){

      foreach ($param['in'] as $key => $val){

        if (!empty($val)) $this->db->where_in($key, $val);

      }

    }

    if(isset($param['customStr'])){

      if (!empty($val)) $this->db->where($param['customStr']);

    }

  }

  /**

   * 新增信息

   * @param string $table 表名称

   * @param array $param 数据变量

   * @return INT ID

   */

  public function add($table = '', $param = array())

  {

    if(empty($table) || !is_array($param) || empty ($param)){

      return FALSE;

    }

    //写入数据表

    $this->db->insert($table, $param);

      array_push($this -> errors,$this->db->last_query());

    //返回记录ID

    return $this->db->insert_id();

  }

  /**

   * 更新分类信息

   * @param string  $table   表名称

   * @param string  $primary  表主键

   * @param int    $id     分类ID

   * @param array   $param   更新的数据

   * @return type

   */

  public function update($table = '', $primary = '', $id = 0, $param = array())

  {

    if(empty($table) || empty($primary) || empty($param) || empty($id))

    {

      return FALSE;

    }

    $id = (int)$id;

    $this->db->where($primary, $id)

         ->limit(1)

         ->update($table, $param);

    array_push($this -> errors,$this->db->last_query());

    return $this->db->affected_rows();

  }

  /**

   * 删除指定ID记录

   * @param string  $table   表名称

   * @param string  $primary  表主键

   * @param array   $id     分类ID

   * @return int

   */

  public function delete($table = '', $primary = '', $id = array()){

    if(empty($table) || empty($primary) || empty($id)){

      return FALSE;

    }

    $this->db->where_in($primary, $id)

        ->delete($table);

    array_push($this -> errors,$this->db->last_query());

    return $this->db->affected_rows();

  }

  /**

   * 获取表的主键

   * @param string  $database  数据库名称

   * @param strting  $table   表名称

   */

  public function getPrimary($table = '', $database = self::dataBase)

  {

    if(empty($database) || empty($table))

    {

      return FALSE;

    }

    $sql = "SELECT k.column_name

        FROM information_schema.table_constraints t

        JOIN information_schema.key_column_usage k

        USING (constraint_name,table_schema,table_name)

        WHERE t.constraint_type='PRIMARY KEY'

         AND t.table_schema='qndnew'

         AND t.table_name='qnd_user'";

    $query = $this->db->query($sql)->result_array();

    return isset($query[0]['column_name']) ? $query[0]['column_name'] : false;

  }

  /**

   * debug sql语句

   */

  public function debugSql(){

    if(count($this->errors) > 0){

      foreach($this->errors as $val){

        echo $val.'<br>';

      }

    }

  }

}

登录后复制

具体的业务逻辑模型如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

class User_model extends My_model {

  const USER = 'qnd_user';

  public $selectFields = array(

    'id',

    'guid',

    'phone',

    'userName',

    'password',

    'headPortraits',

    'nickName',

    'createTime',

  );

  const SMS_ROLE = 'qnd_role';

  public function __construct()

  {

  }

}

登录后复制

控制器中测试如下:

1

2

3

4

5

6

7

8

9

10

11

public function modelTest(){

    $this -> load -> model('User_model'); // 載入 model

    $whereArr = array(

            'compare'=>array(

              'userName' => 'Frank',

            ),

          );

    $rs = $this -> User_model -> pageData('User_model','user',$whereArr);

    print_r($rs);

    $this -> User_model -> debugSql();

  }

登录后复制

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

CI框架中zip类的使用

以上就是CI框架的公共模型类定义与用法的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号