CI (CodeIgniter) Model Usage Example Analysis _php instance

Source: Internet
Author: User
Tags codeigniter
This paper analyzes the CI (codeigniter) model usage. Share to everyone for your reference, as follows:

The business logic in MVC is not appropriate in the controller or in the model, so the business logic is separated and a layer is used to deal with the business logic, and the model is treated as a data access layer, so the sub-model will become lighter. CI does not pass through the entity object to pass the parameter, the parameter's incoming and return are controlled by the developer, more flexible. In many cases, it will be passed in as an array or returned.

The use of the model is also relatively simple, here only to mention a few questions before using it.

1, since already have the data access layer, then we should avoid in the controller or some classes directly through the SQL query database, 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 be very convenient to connect multiple databases, in the database configuration file has talked about the configuration of multiple libraries, according to the different group_name can be easily connected to different libraries. If there is a master-slave, you can also consider the master-slave switching use problems.

3. Does the model have to be differentiated by module? There is a common controller distribution approach in the controller, which may not be good in the model, but can be implemented by inheriting different common model classes, which inherit the My_model of CI. It may be useful to inherit from a module under some business, most of which can be directly inherited my_model,my_model the primary implementation of the database initialization connection and some common methods.

4, the database provides the mode of operation is a comparative basis, we need to assemble according to their own needs, but in our daily operations are similar to many operations, such as, according to the primary key to obtain information, according to the ID to obtain information, according to the attributes to obtain information, etc., can be used for these basic operations in a package, more convenient. Because if you want to use AR way to manipulate the database, you need to remember a lot of methods, such as we based on the user name query:

$query = $this->db->from (' user ')->where (Array (' username ' = ' Bobbypeng '))->get (); return $query Row_array ();

If 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 ();}

By adding a TableName method in each model to return the table name, the method can be easily used by the model.

5, the above method belongs to a common method, we will write in the My_model, but this kind of method will be many, can we use this type of method independent of a file? Because this method is not changed in most cases, the My_model indicates that the modification is open and may affect these methods. If the class is called the ActiveRecord class, then you can let My_model inherit the ActiveRecord class, and the ActiveRecord class inherits Ci_model, the reference code is shown later.

Most of the time the class library provides us with a relatively thin approach, which we can encapsulate to reduce the difficulty of use. The encapsulation of the common methods in the model is still under consideration, the following is a simple operation for a single table, the complex operation has to be implemented in a specific model, there are some common operations or non-AR operation can be unified under, see if there is a chance to consider this issue.

Common AR Package class, for common operations, you need to give DB attribute to database connection object and set several methods in the model, such as primary key, 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 that needs to be inserted * @return A Boolean insert successfully returns ID, insert failure returns false */Public function Save ($data) {    if ($this->db->set ($data)->insert ($this->tablename ())) {return $this->db->insert_id ();  } return FALSE; }/** * Replace data * @param array $data */Public Function replace ($data) {return $this->db->replace ($th  Is->tablename (), $data);  /** * Update record according to primary key * * @param string $PK primary key value * @param array $attributes update field * @param array $where append WHERE Condition * @return Boolean True update succeeded false update failed */Public function updatebypk ($PK, $attributes, $where = Array ()) {$where [$thi    S->primarykey ()] = $PK;  return $this->updateall ($attributes, $where); }/** * Update table record * * @param array $attributes * @param array $where * @return Bollean True update succeeded false update failed */PU Blic function UpdateAll ($attributes, $where = Array ()) {return $this->db->where ($where)->update ($this->tablename (), $attributes)  ;    /** * Delete data based on PRIMARY key * * @param string $PK primary key value * @param array $where Append Delete condition * @return Boolean true Delete succeeded false Delete failed    */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 Row number * @return Boolean true Delete succeeded false Delete failed */ Public Function deleteAll ($where = Array (), $limit = NULL) {return $this->db->delete ($this->tablename (), $WH  Ere, $limit); }/** * Retrieves the * * @param string $PK * @param array $where additional query conditions * @return Array returns a one-dimensional array and returns an empty array if no records are found */pub    Lic function findbypk ($PK, $where = Array ()) {$where [$this->primarykey ()] = $PK;    $query = $this->db->from ($this->tablename ())->where ($where)->get ();  return $query->row_array ();  /** * Get a row of records based on attributes * @param array $where * @return Array returns a one-dimensional array that returns an empty array if no records are found */Public function findbyattributes ($where = Array ()) {    $query = $this->db->from ($this->tablename ())->where ($where)->limit (1)->get ();  return $query->row_array ();  /** * Query Record * * @param array $where query criteria, you can use fuzzy query, such as array (' name like ' = ' + ' pp% ') array (' stat > ' = ' 1 ') * @param int $limit Returns the number of record bars * @param int $offset offset * @param string|array $sort Sort, when an array is: Array (' ID DESC ', ' Report_ Date ASC ') can use the second parameter to control whether escape * @return array not found record returns an empty array */Public function findAll ($where = Array (), $limit = 0, $o    Ffset = 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 (); }/** * Statistics satisfies the total number of conditions * * @param array $where statistics conditions * @return int returns the number of record bars */Public function count ($where = Array ()  {return $this->db->from ($this->tablename ())->where ($where)->count_all_results (); /** * According to SQL query, parameters are bound through $param * @param string $sql query statement, such as SELECT * from some_table where id =? and status =?   and author =? * @param array $param Array (3, ' live ', ' Rick ') * @return array not found return empty array, find records return 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 */

The

My_model can inherit the class so that the method above can be called directly in the child 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 */

More interested in CodeIgniter related content readers can view this site topic: "CodeIgniter Introductory Tutorial" and "CI (codeigniter) Framework Advanced Tutorial"

It is hoped that this article is helpful to the PHP program design based on CodeIgniter framework.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.