Home Backend Development PHP Tutorial Definition and usage of public model classes of CI framework

Definition and usage of public model classes of CI framework

Jun 14, 2018 am 11:51 AM
ci framework codeigniter

This article mainly introduces the definition and usage of the CI framework (CodeIgniter) public model class. It analyzes the definition of the CI framework public model class in the form of specific examples and the related implementation skills of operating the database based on the public model class. Friends who need it can Refer to

The examples in this article describe the definition and usage of the public model classes of the CI framework (CodeIgniter). Share it with everyone for your reference, the details are as follows:

We all know that the methods of operating the database are written in the model. But under normal circumstances, a table often corresponds to at least 4 operations, which is the so-called crud. So if there are 20 tables, the corresponding model methods will reach 80. Repeated operations are obviously a physical job.

Then when operating a single table, we perform a simple encapsulation. The following is an example of the ci framework:

<?php
/**
 * Created by PhpStorm.
 * User: kangjianrong
 * Date: 16-8-26
 * Time: 上午10:29
 */
class My_model extends CI_Model {
  //数据库
  public $errors = array();
  const dataBase = &#39;qndnew&#39;;
  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(&#39;name !=&#39; => $name, &#39;id <&#39; => $id, &#39;date >&#39; => $date);
   *   like(模糊查询)
   *     array(&#39;title&#39; => $match, &#39;page1&#39; => $match, &#39;page2&#39; => $match)
   *   customStr(自定义字符串):
   *     "name=&#39;Joe&#39; AND status=&#39;boss&#39; OR status=&#39;active&#39;"
   *   in:
   *     array(&#39;userName&#39; => array(&#39;Frank&#39;, &#39;Todd&#39;, &#39;James&#39;))
   * @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 = &#39;&#39;, $page = &#39;1&#39;, $limit = &#39;15&#39;, $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(&#39;*&#39;)->from($table);
    }
    //处理查询条件
    if (is_array($param) && count($param) > 0){
      $this -> parseParam($param);
    }
    //统计总数
    if($isReturnCount){
      $rs[&#39;count&#39;]  = $this->db->count_all_results(&#39;&#39;,false);//不重置查询构造器
      array_push($this -> errors,$this->db->last_query());
    }
    //分页数据处理
    if(isset($page) && isset($param[&#39;limit&#39;])){
      //分页边界值 设置
      $offset = $param[&#39;page&#39;] <= 1 ? 0 : ($param[&#39;page&#39;]-1) * $param[&#39;limit&#39;];
      $this->db->limit($param[&#39;limit&#39;], $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, &#39;DESC&#39;);
      }
    }
    $query = $this->db->get();
    array_push($this -> errors,$this->db->last_query());
    $rs[&#39;list&#39;] = $query->result_array();
    return $rs;
  }
  /**
   * 解析参数
   */
  private function parseParam($param){
    if(isset($param[&#39;compare&#39;])){
      foreach ($param[&#39;compare&#39;] as $key => $val){
        if (!empty($val)) $this->db->where($key, $val);
      }
    }
    if(isset($param[&#39;like&#39;])){
      foreach ($param[&#39;like&#39;] as $key => $val){
        if (!empty($val)) $this->db->like($key, $val);
      }
    }
    if(isset($param[&#39;in&#39;])){
      foreach ($param[&#39;in&#39;] as $key => $val){
        if (!empty($val)) $this->db->where_in($key, $val);
      }
    }
    if(isset($param[&#39;customStr&#39;])){
      if (!empty($val)) $this->db->where($param[&#39;customStr&#39;]);
    }
  }
  /**
   * 新增信息
   * @param string $table 表名称
   * @param array $param 数据变量
   * @return INT ID
   */
  public function add($table = &#39;&#39;, $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 = &#39;&#39;, $primary = &#39;&#39;, $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 = &#39;&#39;, $primary = &#39;&#39;, $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 = &#39;&#39;, $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=&#39;PRIMARY KEY&#39;
         AND t.table_schema=&#39;qndnew&#39;
         AND t.table_name=&#39;qnd_user&#39;";
    $query = $this->db->query($sql)->result_array();
    return isset($query[0][&#39;column_name&#39;]) ? $query[0][&#39;column_name&#39;] : false;
  }
  /**
   * debug sql语句
   */
  public function debugSql(){
    if(count($this->errors) > 0){
      foreach($this->errors as $val){
        echo $val.&#39;<br>&#39;;
      }
    }
  }
}
Copy after login

The specific business logic model is as follows:

class User_model extends My_model {
  const USER = &#39;qnd_user&#39;;
  public $selectFields = array(
    &#39;id&#39;,
    &#39;guid&#39;,
    &#39;phone&#39;,
    &#39;userName&#39;,
    &#39;password&#39;,
    &#39;headPortraits&#39;,
    &#39;nickName&#39;,
    &#39;createTime&#39;,
  );
  const SMS_ROLE = &#39;qnd_role&#39;;
  public function __construct()
  {
  }
}
Copy after login

The test in the controller is as follows:

public function modelTest(){
    $this -> load -> model(&#39;User_model&#39;); // 載入 model
    $whereArr = array(
            &#39;compare&#39;=>array(
              &#39;userName&#39; => &#39;Frank&#39;,
            ),
          );
    $rs = $this -> User_model -> pageData(&#39;User_model&#39;,&#39;user&#39;,$whereArr);
    print_r($rs);
    $this -> User_model -> debugSql();
  }
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone’s learning. More For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Use of zip class in CI framework

##

The above is the detailed content of Definition and usage of public model classes of CI framework. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement custom middleware in CodeIgniter How to implement custom middleware in CodeIgniter Jul 29, 2023 am 10:53 AM

How to implement custom middleware in CodeIgniter Introduction: In modern web development, middleware plays a vital role in applications. They can be used to perform some shared processing logic before or after the request reaches the controller. CodeIgniter, as a popular PHP framework, also supports the use of middleware. This article will introduce how to implement custom middleware in CodeIgniter and provide a simple code example. Middleware overview: Middleware is a kind of request

How to use CI framework in php? How to use CI framework in php? Jun 01, 2023 am 08:48 AM

With the development of network technology, PHP has become one of the important tools for Web development. One of the popular PHP frameworks - CodeIgniter (hereinafter referred to as CI) has also received more and more attention and use. Today, we will take a look at how to use the CI framework. 1. Install the CI framework First, we need to download the CI framework and install it. Download the latest version of the CI framework compressed package from CI's official website (https://codeigniter.com/). After the download is complete, unzip

CodeIgniter middleware: Accelerate application responsiveness and page rendering CodeIgniter middleware: Accelerate application responsiveness and page rendering Jul 28, 2023 pm 06:51 PM

CodeIgniter Middleware: Accelerating Application Responsiveness and Page Rendering Overview: As web applications continue to grow in complexity and interactivity, developers need to use more efficient and scalable solutions to improve application performance and responsiveness. . CodeIgniter (CI) is a lightweight PHP-based framework that provides many useful features, one of which is middleware. Middleware is a series of tasks that are performed before or after the request reaches the controller. This article will introduce how to use

How to use the database query builder (Query Builder) in the CodeIgniter framework How to use the database query builder (Query Builder) in the CodeIgniter framework Jul 28, 2023 pm 11:13 PM

Introduction to the method of using the database query builder (QueryBuilder) in the CodeIgniter framework: CodeIgniter is a lightweight PHP framework that provides many powerful tools and libraries to facilitate developers in web application development. One of the most impressive features is the database query builder (QueryBuilder), which provides a concise and powerful way to build and execute database query statements. This article will introduce how to use Co

Use PHP framework CodeIgniter to develop a real-time chat application to provide convenient communication services Use PHP framework CodeIgniter to develop a real-time chat application to provide convenient communication services Jun 27, 2023 pm 02:49 PM

With the development of mobile Internet, instant messaging has become more and more important and popular. For many companies, live chat is more like a communication service, providing a convenient communication method that can quickly and effectively solve business problems. Based on this, this article will introduce how to use the PHP framework CodeIgniter to develop a real-time chat application. Understand the CodeIgniter framework CodeIgniter is a lightweight PHP framework that provides a series of simple tools and libraries to help developers quickly

PHP development: Using CodeIgniter to implement MVC pattern and RESTful API PHP development: Using CodeIgniter to implement MVC pattern and RESTful API Jun 16, 2023 am 08:09 AM

As web applications continue to evolve, it is important to develop applications more quickly and efficiently. And, as RESTful API is widely used in web applications, it is necessary for developers to understand how to create and implement RESTful API. In this article, we will discuss how to implement MVC pattern and RESTful API using CodeIgniter framework. Introduction to MVC pattern MVC (Model-Vie

CodeIgniter middleware: Provides secure file upload and download functions CodeIgniter middleware: Provides secure file upload and download functions Aug 01, 2023 pm 03:01 PM

CodeIgniter middleware: Provides secure file upload and download functions Introduction: In the process of web application development, file upload and download are very common functions. However, for security reasons, handling file uploads and downloads often requires additional security measures. CodeIgniter is a popular PHP framework that provides a wealth of tools and libraries to support developers in building secure and reliable web applications. This article will introduce how to use CodeIgniter middleware to implement secure files

How to use CodeIgniter5 framework in php? How to use CodeIgniter5 framework in php? Jun 01, 2023 am 11:21 AM

CodeIgniter is a lightweight PHP framework that uses MVC architecture to support rapid development and simplify common tasks. CodeIgniter5 is the latest version of the framework and offers many new features and improvements. This article will introduce how to use the CodeIgniter5 framework to build a simple web application. Step 1: Install CodeIgniter5 Downloading and installing CodeIgniter5 is very simple, just follow these steps: Download the latest version

See all articles