CI (CodeIgniter) model usage example analysis, cicodeigniter_PHP tutorial

WBOY
Release: 2016-07-12 09:00:03
Original
962 people have browsed it

CI (CodeIgniter) model usage example analysis, cicodeigniter

This article analyzes the CI (CodeIgniter) model usage example. Share it with everyone for your reference, the details are as follows:

It is inappropriate to place the business logic in MVC in the controller or the model, so the business logic is separated here. An extra layer is used to process the business logic, and the model is only used as the data access layer. This way the model will become lighter. In CI, parameters are not passed through entity objects. The input and return of parameters are controlled by the developer, which is more flexible. In many cases, it is passed in or returned as an array.

The use of the model is also relatively simple. Here are just a few questions that come to mind before use.

1. Since we already have a data access layer, we should avoid querying the database directly through SQL in the controller or certain classes. All database access operations should be obtained through the model. In most cases, a table The name corresponds to a model class.

2. The model should be easy to connect to multiple databases. The configuration of multiple libraries is discussed in the database configuration file. Different libraries can be easily connected according to the group_name. If there is a master-slave, you can also consider the issue of master-slave switching.

3. Do models need to be distinguished by modules? There is a practice of public controller distribution in the controller. This kind of thinking may not be good in the model, but it can be achieved by inheriting different public model classes, and these classes then inherit the MY_Model of CI. In some businesses, it may be useful to inherit based on modules. In most cases, you can directly inherit MY_Model. MY_Model mainly implements the initialization connection of the database and some public methods.

4. The operation methods provided by the database are relatively basic and require us to assemble them according to our own needs. However, many operations in our daily operations are similar, such as obtaining information based on the primary key, obtaining information based on the ID, and obtaining information based on the ID. Attribute acquisition information, etc., these basic operations can be encapsulated at once, making it more convenient to use. Because if you want to use AR to operate the database, you need to remember many methods. For example, if we query based on user name:

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

Copy after login

If it is encapsulated, you only need to remember one method, such as:

public function findByAttributes($where = array())
{
  $query = $this->db->from($this->tableName())->where($where)->get();
  return $query->row_array();
}

Copy after login

In this way, after the method of adding a tableName in each model returns the table name, you can easily use this method through the model.

5. The above method is a public method. We will write it in MY_Model, but there will be many similar methods. Can we separate this type of method into a file? Because this method will not change in most cases, placing it in MY_Model means that it is open to modification, which may affect these methods. If this class is called the ActiveRecord class, then MY_Model can inherit the ActiveRecord class, and the ActiveRecord class can inherit CI_Model. See the reference code below.

Many times, the methods provided to us by class libraries are relatively detailed, and we can encapsulate them to reduce the difficulty of use. The encapsulation of public methods in the model has been under consideration. What is given below is only a simple operation for a single table. Complex operations must be implemented in a specific model. There are also some public operations or non-AR operations. The methods can be unified and we will see if we have the opportunity to consider this issue again in the future.

Public AR encapsulation class, which can perform common operations. You need to assign the db attribute as the database connection object and set several methods in the model, such as primary key and table name

<&#63;php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ActiveRecord extends CI_Model
{
  /**
   * 保存数据
   * 
   * @param array $data 需要插入的表数据
   * @return boolean 插入成功返回ID,插入失败返回false
   */
  public function save($data)
  {
    if($this->db->set($data)->insert($this->tableName())) {
      return $this->db->insert_id();
    }
    return FALSE;
  }
  /**
   * Replace数据
   * @param array $data
   */
  public function replace($data)
  {
    return $this->db->replace($this->tableName(), $data);
  }
  /**
   * 根据主键更新记录
   * 
   * @param string $pk 主键值
   * @param array $attributes 更新字段
   * @param array $where 附加where条件
   * @return boolean true更新成功 false更新失败
   */
  public function updateByPk($pk, $attributes, $where = array())
  {
    $where[$this->primaryKey()] = $pk;
    return $this->updateAll($attributes, $where);
  }
  /**
   * 更新表记录
   * 
   * @param array $attributes
   * @param array $where
   * @return bollean true更新成功 false更新失败
   */
  public function updateAll($attributes, $where = array())
  {
    return $this->db->where($where)->update($this->tableName(), $attributes);
  }
  /**
   * 根据主键删除数据
   * 
   * @param string $pk 主键值
   * @param array $where 附加删除条件
   * @return boolean true删除成功 false删除失败 
   */
  public function deleteByPk($pk, $where = array())
  {
    $where[$this->primaryKey()] = $pk;
    return $this->deleteAll($where);
  }
  /**
   * 删除记录
   * 
   * @param array $where 删除条件
   * @param int $limit 删除行数
   * @return boolean true删除成功 false删除失败
   */
  public function deleteAll($where = array(), $limit = NULL)
  {
    return $this->db->delete($this->tableName(), $where, $limit);
  }
  /**
   * 根据主键检索
   * 
   * @param string $pk
   * @param array $where 附加查询条件
   * @return array 返回一维数组,未找到记录则返回空数组
   */
  public function findByPk($pk, $where = array())
  {
    $where[$this->primaryKey()] = $pk;
    $query = $this->db->from($this->tableName())->where($where)->get();
    return $query->row_array();
  }
  /**
   * 根据属性获取一行记录
   * @param array $where
   * @return array 返回一维数组,未找到记录则返回空数组
   */
  public function findByAttributes($where = array())
  {
    $query = $this->db->from($this->tableName())->where($where)->limit(1)->get();
    return $query->row_array();
  }
  /**
   * 查询记录
   * 
   * @param array $where 查询条件,可使用模糊查询,如array('name LIKE' => "pp%") array('stat >' => '1')
   * @param int $limit 返回记录条数
   * @param int $offset 偏移量
   * @param string|array $sort 排序, 当为数组的时候 如:array('id DESC', 'report_date ASC')可以通过第二个参数来控制是否escape
   * @return array 未找到记录返回空数组
   */
  public function findAll($where = array(), $limit = 0, $offset = 0, $sort = NULL)
  {
    $this->db->from($this->tableName())->where($where);
    if($sort !== NULL) {
      if(is_array($sort)){
        foreach($sort as $value){
          $this->db->order_by($value, '', false);
        }
      } else {
        $this->db->order_by($sort);
      }
    }
    if($limit > 0) {
      $this->db->limit($limit, $offset);
    }
    $query = $this->db->get();
    return $query->result_array();
  }
  /**
   * 统计满足条件的总数
   * 
   * @param array $where 统计条件
   * @return int 返回记录条数
   */
  public function count($where = array())
  {
    return $this->db->from($this->tableName())->where($where)->count_all_results();
  }
  /**
   * 根据SQL查询, 参数通过$param绑定
   * @param string $sql 查询语句,如SELECT * FROM some_table WHERE id = &#63; AND status = &#63; AND author = &#63;
   * @param array $param array(3, 'live', 'Rick')
   * @return array 未找到记录返回空数组,找到记录返回二维数组
   */
  public function query($sql, $param = array())
  {
    $query = $this->db->query($sql, $param);
    return $query->result_array();
  }
}
/* End of file ActiveRecord.php */
/* Location: ./application/core/database/ActiveRecord.php */

Copy after login

MY_Model can inherit this class, so that the above method can be directly called in the sub-model.

<&#63;php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH.'core/database/ActiveRecord.php';
class MY_Model extends ActiveRecord 
{
  public function __construct($group_name = '')
  {
    $this->initDb($group_name);
    parent::__construct();
  }
  protected function initDb($group_name = '')
  {
    $db_conn_name = $this->getDbName($group_name);
    $CI = & get_instance();
    if(isset($CI->{$db_conn_name}) && is_object($CI->{$db_conn_name})) {
      $this->db = $CI->{$db_conn_name};
    } else {
      $CI->{$db_conn_name} = $this->db = $this->load->database($group_name, TRUE);
    }
  }
  private function getDbName($group_name = '')
  {
    if($group_name == '') {
      $db_conn_name = 'db';
    } else {
      $db_conn_name = 'db_'.$group_name;
    }
    return $db_conn_name;
  }
}
/* End of file MY_Model.php */
/* Location: ./application/core/MY_Model.php */

Copy after login

Readers who are interested in more CodeIgniter related content can check out the special topics on this site: "codeigniter introductory tutorial" and "CI (CodeIgniter) framework advanced tutorial"

I hope this article will be helpful to everyone’s PHP program design based on the CodeIgniter framework.

Articles you may be interested in:

  • CodeIgniter custom controller MY_Controller usage analysis
  • Codeigniter controller controller inheritance problem example analysis
  • 2 Codeigniter Example of writing batch file upload controller
  • Detailed explanation of CodeIgniter hook usage example
  • CodeIgniter configuration database.php usage example analysis
  • Detailed explanation of CodeIgniter multi-language implementation method
  • Notes on using the CodeIgniter view
  • Detailed explanation of the codeIgniter read-write separation implementation method
  • CI (CodeIgniter) simple statistical visitor number implementation method
  • CodeIgniter controller business logic example analysis

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1094765.htmlTechArticleCI (CodeIgniter) model usage example analysis, cicodeigniter This article analyzes the CI (CodeIgniter) model usage example. Share it with everyone for your reference, the details are as follows: The business logic in MVC is placed...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template