This article mainly introduces the CI (CodeIgniter) model usage, and analyzes the functions, usage, and precautions of the model in the CodeIgniter framework based on examples, for more information about CI (CodeIgniter) model usage, see the following example. We will share this with you for your reference. The details are as follows:
The business logic in MVC is not suitable in the controller or model. Therefore, the business logic is separated here. an additional layer is used to process the business logic, and the model is only used as the data access layer, in this way, the model will become lighter. In CI, parameters are not passed through object. the input and return of parameters are controlled by developers and flexible. In many cases, it is passed in or returned as an array.
The model is also relatively simple to use. here we will only mention a few questions that have occurred before use.
1. since the data access layer already exists, we should avoid directly querying the database through SQL in the controller or some classes. all database access operations should be obtained through the model, in most cases, a table name corresponds to a model class.
2. the model should easily connect to multiple databases. in the database configuration file, you can easily connect to different databases based on group_name. If there is a master-slave node, you can also consider the use of the master-slave switch.
3. do models need to be differentiated by modules? There is a public controller distribution method in the controller. in the model, this thinking may not be very good, but it can be achieved by inheriting different public model classes, which inherit the CI MY_Model. In some services, inheritance by module may be useful. In most cases, MY_Model can be inherited directly. MY_Model mainly implements database initialization connections and some public methods.
4. The operation methods provided by the database are relatively basic and need to be assembled according to our own needs. However, many operations are similar in our daily operations, for example, obtaining information based on the primary key, you can encapsulate the basic operations based on the ID and attributes for ease of use. If you want to use AR to operate the database, you need to remember many methods, such as querying by user name:
$query = $this->db->from('user')->where(array('username' => 'BobbyPeng'))->get();return $query->row_array();
After encapsulation, you only need to remember one method, for example:
public function findByAttributes($where = array()){ $query = $this->db->from($this->tableName())->where($where)->get(); return $query->row_array();}
In this way, you can add a tableName method to each model to return the table name, and then 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 from a file? This method is not changed in most cases, but in MY_Model, it indicates that the modification is made open to it, which may affect these methods. If the class is called the ActiveRecord class, you can let MY_Model inherit the ActiveRecord class, and the ActiveRecord class inherit the CI_Model class. see the code below.
Most of the time, the methods provided by the class library are relatively fine. we can encapsulate them to reduce the difficulty. The encapsulation of common methods in the model is still under consideration. The following 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 that can be unified to see if there is a chance to come back and consider this issue.
Common AR encapsulation class, which can be used for common operations. you need to assign the db attribute to 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 {/*** save data ** @ param array $ data the table data to be inserted * @ return boolean return ID after successful insertion, if insertion fails, false */public function save ($ data) {if ($ this-> db-> set ($ data) is returned) -> insert ($ this-> tableName () {return $ this-> db-> insert_id ();} return FALSE ;} /*** Replace data ** @ param array $ data */public function replace ($ data) {return $ t His-> db-> replace ($ this-> tableName (), $ data );} /*** UPDATE record based on primary key ** @ param string $ pk primary key value * @ param array $ attributes update field * @ param array $ where append where condition * @ return boolean true update failed to update false */public function updateByPk ($ pk, $ attributes, $ where = array () {$ where [$ this-> primaryKey ()] = $ pk; return $ this-> updateAll ($ attributes, $ where);}/*** Update Table record ** @ param array $ attributes * @ param array $ whe Re * @ return bollean true update successful false update failed */public function updateAll ($ attributes, $ where = array ()) {return $ this-> db-> where ($ where)-> update ($ this-> tableName (), $ attributes );} /*** delete data based on the primary key ** @ param string $ pk primary key value * @ param array $ where append the deletion condition * @ return boolean true success false deletion failure */public function deleteByPk ($ pk, $ where = array () {$ where [$ this-> primaryKey ()] = $ pk; return $ this-> deleteAll ($ Where );} /***** delete record ** @ param array $ where delete condition * @ param int $ limit delete rows * @ return boolean true delete successful false delete failed */public function deleteAll ($ where = array (), $ limit = NULL) {return $ this-> db-> delete ($ this-> tableName (), $ where, $ limit );} /*** search by primary key ** @ param string $ pk * @ param array $ where append query condition * @ return array returns a one-dimensional array, if no record is found, an empty array */public function findByPk ($ pk, $ where = array () {$ where [$ This-> primaryKey ()] = $ pk; $ query = $ this-> db-> from ($ this-> tableName ()-> where ($ where) -> get (); return $ query-> row_array ();}/*** obtain a row of records based on attributes * @ param array $ where * @ return array returns a one-dimensional array, if no record is found, an empty array */public function findByAttributes ($ where = array () is returned ()) {$ query = $ this-> db-> from ($ this-> tableName ()-> where ($ where)-> limit (1)-> get (); return $ query-> row_array ();}/*** query record ** @ param array $ where query Condition, you can use fuzzy query, such as array ('name LIKE '=> "pp %") array ('stat>' => '1 ') * @ param int $ limit returns the number of records * @ param int $ offset * @ param string | array $ sort sorting, for example, array ('Id DESC ', 'report _ date ASC ') you can use the second parameter to control whether escape * @ return array does not find the record to return an empty 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 ();} /*** count the total number of records meeting the condition ** @ param array $ where statistical condition * @ return int returns the number of records */public function count ($ where = array ()) {return $ this-> db-> from ($ this-> table Name ()-> where ($ where)-> count_all_results ();}/*** according to the SQL query, the parameter is bound through $ param * @ param string $ SQL query statement, for example, SELECT * FROM some_table WHERE id =? AND status =? AND author =? * @ Param array $ param array (3, 'live', 'Rick ') * @ return array no record is found and an empty array is returned, returns a two-dimensional 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 the class, so that the above method can be directly called in the 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 */