A-A+

CI(CodeIgniter)模型用法实例分析

2021年07月06日 我爱编程 暂无评论

本文实例分析了CI(CodeIgniter)模型用法,分享给大家供大家参考,具体如下:

MVC中的业务逻辑放在控制器中或者模型里都是不合适的,所以这里对业务逻辑进行了分离,多出一层用来处理业务逻辑,模型就只当作数据访问层,这样子模型将会变得比较轻。CI中并未通过实体对象来传参,参数的传入和返回都由开发者控制,比较灵活。很多情况下都会以数组的方式传入或者返回。

模型的使用也比较简单,这里只提一下使用前想到的几个问题吧。

1、既然已经有了数据访问层了,那我们就应当避免在控制器或者某些类中直接通过SQL查询数据库,所有的数据库访问操作都应当经过模型获取,大多数情况下一个表名对应着一个模型类。

2、模型应当很方便的连接多个数据库,在database配置文件中有谈到多个库的配置问题,根据group_name的不同可以很方便的连接不同的库。如果有主从,还可以考虑到主从的切换使用问题。

3、模型是否还要按模块区分?在控制器中存在公用控制器分发的做法,在模型中这种思维可能不太好,但可以通过继承不同的公用模型类来实现,这些类再继承CI的MY_Model。在某些业务下根据模块来继承可能比较有用,大部分情况可以直接继承MY_Model,MY_Model主要实现数据库的初始化连接以及一些公用方法。

4、数据库提供的操作方式都是比较基础的,需要我们根据自身的需求去组装,但在我们日常操作中很多操作是类似的,如,根据主键获取信息,根据ID获取信息,根据属性获取信息等,可以对这些基础的操作在进行一次封装,更方便使用。因为如果要使用AR的方式来操作数据库,需要记住很多的方法,如我们根据用户名查询:

$query = $this->db->from('user')->where(array('username' => 'BobbyPeng'))->get();

return $query->row_array();

如果封装后,则只需要记住一个方法即可,如:

  1. public function findByAttributes($where = array())
  2. {
  3.   $query = $this->db->from($this->tableName())->where($where)->get();
  4.   return $query->row_array();
  5. }

这样子在每个模型中添加一个tableName的方法返回表名后,再通过模型就可以很方便的使用该方法了。

5、上面的方法属于一个公用方法,我们会写在MY_Model中,但这种类似的方法会很多,我们可否将该类型的方法独立于一个文件中?因为这种方法大部分情况下是不会改的,而放在MY_Model中则表示对它的修改开放了,可能会影响到这些方法。如果说该类叫ActiveRecord类,那可以让MY_Model继承ActiveRecord类,而ActiveRecord类继承CI_Model,参考代码见后面。

很多时候类库提供给我们的方法都是比较细的,我们可以封装一下,减少使用难度。关于模型中公用方法的封装一直还在考虑中,下面给出的只是一个针对单表的简单的操作,复杂的操作就得在特定的模型中实现,还有一些公用操作或者说非AR的操作方式可以统一下,看以后是否有机会再来考虑下这个问题。

公用AR封装类,可进行常用的操作,需要赋予db属性为数据库连接对象,并在模型中设置几个方法,如主键、表名

  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. class ActiveRecord extends CI_Model
  3. {
  4.   /**
  5.    * 保存数据
  6.    * 
  7.    * @param array $data 需要插入的表数据
  8.    * @return boolean 插入成功返回ID,插入失败返回false
  9.    */
  10.   public function save($data)
  11.   {
  12.     if($this->db->set($data)->insert($this->tableName())) {
  13.       return $this->db->insert_id();
  14.     }
  15.     return FALSE;
  16.   }
  17.   /**
  18.    * Replace数据
  19.    * @param array $data
  20.    */
  21.   public function replace($data)
  22.   {
  23.     return $this->db->replace($this->tableName(), $data);
  24.   }
  25.   /**
  26.    * 根据主键更新记录
  27.    * 
  28.    * @param string $pk 主键值
  29.    * @param array $attributes 更新字段
  30.    * @param array $where 附加where条件
  31.    * @return boolean true更新成功 false更新失败
  32.    */
  33.   public function updateByPk($pk$attributes$where = array())
  34.   {
  35.     $where[$this->primaryKey()] = $pk;
  36.     return $this->updateAll($attributes$where);
  37.   }
  38.   /**
  39.    * 更新表记录
  40.    * 
  41.    * @param array $attributes
  42.    * @param array $where
  43.    * @return bollean true更新成功 false更新失败
  44.    */
  45.   public function updateAll($attributes$where = array())
  46.   {
  47.     return $this->db->where($where)->update($this->tableName(), $attributes);
  48.   }
  49.   /**
  50.    * 根据主键删除数据
  51.    * 
  52.    * @param string $pk 主键值
  53.    * @param array $where 附加删除条件
  54.    * @return boolean true删除成功 false删除失败 
  55.    */
  56.   public function deleteByPk($pk$where = array())
  57.   {
  58.     $where[$this->primaryKey()] = $pk;
  59.     return $this->deleteAll($where);
  60.   }
  61.   /**
  62.    * 删除记录
  63.    * 
  64.    * @param array $where 删除条件
  65.    * @param int $limit 删除行数
  66.    * @return boolean true删除成功 false删除失败
  67.    */
  68.   public function deleteAll($where = array(), $limit = NULL)
  69.   {
  70.     return $this->db->delete($this->tableName(), $where$limit);
  71.   }
  72.   /**
  73.    * 根据主键检索
  74.    * 
  75.    * @param string $pk
  76.    * @param array $where 附加查询条件
  77.    * @return array 返回一维数组,未找到记录则返回空数组
  78.    */
  79.   public function findByPk($pk$where = array())
  80.   {
  81.     $where[$this->primaryKey()] = $pk;
  82.     $query = $this->db->from($this->tableName())->where($where)->get();
  83.     return $query->row_array();
  84.   }
  85.   /**
  86.    * 根据属性获取一行记录
  87.    * @param array $where
  88.    * @return array 返回一维数组,未找到记录则返回空数组
  89.    */
  90.   public function findByAttributes($where = array())
  91.   {
  92.     $query = $this->db->from($this->tableName())->where($where)->limit(1)->get();
  93.     return $query->row_array();
  94.   }
  95.   /**
  96.    * 查询记录
  97.    * 
  98.    * @param array $where 查询条件,可使用模糊查询,如array('name LIKE' => "pp%") array('stat >' => '1')
  99.    * @param int $limit 返回记录条数
  100.    * @param int $offset 偏移量
  101.    * @param string|array $sort 排序, 当为数组的时候 如:array('id DESC', 'report_date ASC')可以通过第二个参数来控制是否escape
  102.    * @return array 未找到记录返回空数组
  103.    */
  104.   public function findAll($where = array(), $limit = 0, $offset = 0, $sort = NULL)
  105.   {
  106.     $this->db->from($this->tableName())->where($where);
  107.     if($sort !== NULL) {
  108.       if(is_array($sort)){
  109.         foreach($sort as $value){
  110.           $this->db->order_by($value'', false);
  111.         }
  112.       } else {
  113.         $this->db->order_by($sort);
  114.       }
  115.     }
  116.     if($limit > 0) {
  117.       $this->db->limit($limit$offset);
  118.     }
  119.     $query = $this->db->get();
  120.     return $query->result_array();
  121.   }
  122.   /**
  123.    * 统计满足条件的总数
  124.    * 
  125.    * @param array $where 统计条件
  126.    * @return int 返回记录条数
  127.    */
  128.   public function count($where = array())
  129.   {
  130.     return $this->db->from($this->tableName())->where($where)->count_all_results();
  131.   }
  132.   /**
  133.    * 根据SQL查询, 参数通过$param绑定
  134.    * @param string $sql 查询语句,如SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?
  135.    * @param array $param array(3, 'live', 'Rick')
  136.    * @return array 未找到记录返回空数组,找到记录返回二维数组
  137.    */
  138.   public function query($sql$param = array())
  139.   {
  140.     $query = $this->db->query($sql$param);
  141.     return $query->result_array();
  142.   }
  143. }
  144. /* End of file ActiveRecord.php */
  145. /* Location: ./application/core/database/ActiveRecord.php */

MY_Model可以继承该类,这样子模型中可以直接调用上面的方法。

  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. require_once APPPATH.'core/database/ActiveRecord.php';
  3. class MY_Model extends ActiveRecord
  4. {
  5.   public function __construct($group_name = '')
  6.   {
  7.     $this->initDb($group_name);
  8.     parent::__construct();
  9.   }
  10.   protected function initDb($group_name = '')
  11.   {
  12.     $db_conn_name = $this->getDbName($group_name);
  13.     $CI = & get_instance();
  14.     if(isset($CI->{$db_conn_name}) && is_object($CI->{$db_conn_name})) {
  15.       $this->db = $CI->{$db_conn_name};
  16.     } else {
  17.       $CI->{$db_conn_name} = $this->db = $this->load->database($group_name, TRUE);
  18.     }
  19.   }
  20.   private function getDbName($group_name = '')
  21.   {
  22.     if($group_name == '') {
  23.       $db_conn_name = 'db';
  24.     } else {
  25.       $db_conn_name = 'db_'.$group_name;
  26.     }
  27.     return $db_conn_name;
  28.   }
  29. }
  30. /* End of file MY_Model.php */
  31. /* Location: ./application/core/MY_Model.php */

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录