


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();
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(); }
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
<?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 = ? AND status = ? AND author = ? * @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 */
MY_Model can inherit this class, so that the above method can be directly called in the sub-model.
<?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 */
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

如何在CodeIgniter中实现自定义中间件引言:在现代的Web开发中,中间件在应用程序中起着至关重要的作用。它们可以用来执行在请求到达控制器之前或之后执行一些共享的处理逻辑。CodeIgniter作为一个流行的PHP框架,也支持中间件的使用。本文将介绍如何在CodeIgniter中实现自定义中间件,并提供一个简单的代码示例。中间件概述:中间件是一种在请求

CodeIgniter中间件:加速应用程序的响应速度和页面渲染概述:随着网络应用程序的复杂性和交互性不断增长,开发人员需要使用更加高效和可扩展的解决方案来提高应用程序的性能和响应速度。CodeIgniter(CI)是一种基于PHP的轻量级框架,提供了许多有用的功能,其中之一就是中间件。中间件是在请求到达控制器之前或之后执行的一系列任务。这篇文章将介绍如何使用

在CodeIgniter框架中使用数据库查询构建器(QueryBuilder)的方法引言:CodeIgniter是一个轻量级的PHP框架,它提供了许多功能强大的工具和库,方便开发人员进行Web应用程序开发。其中一个令人印象深刻的功能是数据库查询构建器(QueryBuilder),它提供了一种简洁而强大的方法来构建和执行数据库查询语句。本文将介绍如何在Co

随着网站建设的不断发展和升级,选择适合自己的框架已经成为建站者必备技能。本文将对CI和Laravel进行简要分析,帮您选出更适合构建博客或CMS网站的框架。一、CI介绍CodeIgniter,简称CI,是一个开源的轻量级web应用程序开发框架,采用MVC架构模式。CI可运行于PHP5.2及以上版本,并包含了许多常用的库和帮助函数,使得使用CI开发web应用程

随着Web应用程序的不断发展,更加快速和高效地开发应用程序变得非常重要。并且,随着RESTfulAPI在Web应用程序中的广泛应用,对于开发人员来说,必须理解如何创建和实现RESTfulAPI。在本文中,我们将讨论如何使用CodeIgniter框架实现MVC模式和RESTfulAPI。MVC模式简介MVC(Model-Vie

CodeIgniter是一个轻量级的PHP框架,采用MVC架构,支持快速开发和简化常见任务。CodeIgniter5是该框架的最新版本,提供了许多新的特性和改进。本文将介绍如何使用CodeIgniter5框架来构建一个简单的Web应用程序。步骤1:安装CodeIgniter5下载和安装CodeIgniter5非常简单,只需要遵循以下步骤:下载最新版本

现今互联网时代,一款深受用户喜爱的网站必须具备简洁明了的前端界面和功能强大的后台管理系统,而PHP框架CodeIgniter则是一款能够让开发者快速搭建后台管理系统的优秀框架。CodeIgniter拥有轻量级、高效率、易扩展等特点,本文将针对初学者,详细说明如何通过该框架快速搭建一个后台管理系统。一、安装配置安装PHPCodeIgniter是一个基于PHP的

近年来,Web开发技术的进步和全球互联网应用的不断扩大,使得PHP技术应用面越来越广泛。作为一种快速开发的技术,其生态系统也在不断发展壮大。其中,CodeIgniter作为PHP开发领域中著名的框架之一,备受众多开发者的欢迎。本篇文章将介绍CodeIgniter框架的相关知识,以此为初学者提供一个入门的指引。一、什么是CodeIgniter框架?CodeIg


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
