CI (CodeIgniter) Model Usage Example Analysis _php instance

Source: Internet
Author: User

The usage of CI (CodeIgniter) model is analyzed in this paper. Share to everyone for your reference, specific as follows:

The business logic in MVC is not appropriate in the controller or in the model, so the business logic is decoupled, a layer is used to handle the business logic, and the model is treated as a data access layer, so that the child model becomes lighter. CI does not pass the entity object to pass the parameter, the parameter's incoming and the return are controlled by the developer, is more flexible. In many cases, they are passed in or returned as arrays.

The use of the model is also relatively simple, here only to mention some of the problems before the use of it.

1, now that there is a 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 corresponding 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 very convenient to connect different libraries. If you have master and subordinate, you can also consider the master-slave switching use problem.

3. Does the model have to be differentiated by module? The practice of public controller distribution in the controller may not be good in the model, but it can be implemented by inheriting different common model classes that inherit CI my_model. It may be useful to inherit from a module in some businesses, most of which can directly inherit My_model,my_model primary implementation of the database initialization connection and some common methods.

4, the database provides the mode of operation are relatively basic, we need to assemble according to their own needs, but in our day-to-day operations many of the operations are similar, such as, according to the primary key to obtain information, according to the ID to obtain information, according to the property to obtain information, and so on, these basic operations in a package, more convenient to use. Because if you want to use AR to manipulate the database, you need to remember a lot of ways, such as we query according to user name:

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

If you encapsulate it, you just 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 ();
}

This makes it easy to use the model by adding a TableName method to each model to return the table name.

5, the above method belongs to a common method, we will write in the My_model, but this kind of similar method will be many, can we make this kind of method independent in a file? Because this method is not changed in most cases, in My_model it means that changes to it are open and may affect these methods. If this class is called the ActiveRecord class, that can let My_model inherit ActiveRecord class, and ActiveRecord class inherits Ci_model, the reference code see back.

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

Public AR Encapsulation class, you can do common operations, you need to give the DB property to the database connection object, and in the model set several methods, 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 table data to insert * @return Boolean insert successful return ID  , insert failed to return 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-&GT;DB-&GT;REPL
  Ace ($this->tablename (), $data); /** * Update record by primary key * @param string $PK primary key value * @param array $attributes update field * @param array $where append where
    Condition * @return Boolean True update success false update failed/Public function updatebypk ($PK, $attributes, $where = Array ()) {
    $where [$this->primarykey ()] = $PK;
  return $this->updateall ($attributes, $where); /** * Update table record * @param array $attributes * @param array $where * @return Bollean True Update succeeded False update failed/Public 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 Additional Delete condition * @return Boolean true Delete success 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 rows * @return Boolean true Delete succeeded false Delete failed */Public Function DeleteAll ($where = Array (), $limit = NULL) {return $this->db->delete ($this->tablen
  Ame (), $where, $limit);
   /** * Search by PRIMARY KEY * * @param string $PK * @param array $where additional query conditions * @return Array returns a one-dimensional array, and an empty array is returned if no records are found
    */Public Function findbypk ($PK, $where = Array ()) {$where [$this->primarykey ()] = $PK; $query = $this->db->from ($this->tablename ())->wHere ($where)->get ();
  return $query->row_array (); /** * Gets a row of records based on properties * @param array $where * @return Array returns a one-dimensional array, and no records are found returns an empty array/public function Findbyattri Butes ($where = Array ()) {$query = $this->db->from ($this->tablename ())->where ($where)->limit (1)->g
    ET ();
  return $query->row_array (); 
   /** * Query Record * * @param array $where query criteria, you can use fuzzy queries 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 array: Array (' ID DESC ', ' Report_date ASC ') can be controlled by the second parameter to escape * @return array not found record returns an empty array/Public function findall ($where = Array (), $lim
    it = 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 ($val
        UE, ', false '; } else {$thiS->db->order_by ($sort);
    } if ($limit > 0) {$this->db->limit ($limit, $offset);
    $query = $this->db->get ();
  return $query->result_array (); /** * Statistics meet the total number of conditions * * @param array $where Statistical 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 (); /** * Based on SQL queries, parameters are $sql query statements by $param binding * @param string, such as SELECT * from some_table where id =? and status =?
   and author =? * @param array $param Array (3, ' live ', ' Rick ') * @return Array did not find the record returns an empty array, finds the record 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/*

The

My_model can inherit the class so that the above method can be called directly from the child model.

 <?php if (! defined (' BasePath ')) exit (' No Direct script access allowed '); require_once Apppat
H. ' core/database/activerecord.php '; Class My_model extends ActiveRecord {public function __construct ($group _name = ') {$this->initdb ($group _nam
    e);
  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);
    The 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 readers interested in CodeIgniter-related content can view the site topics: "CodeIgniter Introductory Course" and "CI (CodeIgniter) Framework Advanced Course"

I hope this article will help you with the PHP program design based on CodeIgniter framework.

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.