Common model class definition and usage of CI framework

Source: Internet
Author: User
Tags codeigniter
This article mainly introduces the definition and usage of CI Framework (CodeIgniter) Public model class, analyzes the definition of CI Framework public model class and the related implementation technique based on the common model class operation database, in combination with concrete instance form, and the need of friends can refer to

This article describes the definition and usage of the CI Framework (CodeIgniter) public model class. Share to everyone for your reference, as follows:

As we all know, the methods of manipulating the database are written in the model. But in general, a table often corresponds to at least 4 operations, the so-called crud. So if 20 tables, the corresponding model method, reached 80, repeat the operation is obviously this is a manual work.

So when it comes to single-table operations, let's take a simple package. The following is an example of the CI framework:

<?php/** * Created by Phpstorm.   * User:kangjianrong * date:16-8-26 * time: Morning 10:29 */class My_model extends Ci_model {//Database public $errors = Array ();  Const DataBase = ' qndnew ';  Public Function __construct () {//Call the Ci_model constructor parent::__construct (); }/** * Querying paging data (used for simple single-table operations) * @param string $model Model Example: User_model * @param string $table table name * @param string $select _fields to display fields * @param array $param query criteria: * Compare (comparison): * Array ($key + $val) $key is the field to be manipulated, $val the   Value * Array (' name! = ' = $name, ' id < ' = $id, ' date > ' + $date);   * Like (fuzzy query) * Array (' title ' = = $match, ' Page1 ' + $match, ' page2 ' = + $match) * CUSTOMSTR (custom string): * "Name= ' Joe ' and status= ' boss ' OR status= ' active '" * In: * Array (' userName ' + = Array (' Frank ', ' Todd ', ' J Ames ') * @param string $page The current number of pages (set to empty when querying all data) * @param string $limit query bar (set to empty when querying all data) * @param array $order sort bar Pieces: * Array ($key = = $val) * $key the field to sort by, * $val Sort by "ASC (ascending, default) or desc (descending), or random" * @ $isReturnCount Boole returns the total bar  Number * @return Array|boolean * * */Public Function pagedata ($model, $table, $param = Array (), $select _fields = ", $page    = ' 1 ', $limit = ' ", $order = Array (), $isReturnCount = True) {if (empty ($model) | | empty ($table)) {return false;    } $this-Load model ($model);    $table = $this->db->dbprefix. $table;    Process the Query field if (!empty ($select _fields)) {$this->db->select ($select _fields)->from ($table); }elseif (Isset ($this, $model, selectfields) {$this->db->select ($model, $this, Selectfields)    ->from ($table);    }else{$this->db->select (' * ')->from ($table);    }//Processing query conditions if (Is_array ($param) && count ($param) > 0) {$this-ParseParam ($param);    }//Total statistics if ($isReturnCount) {$rs [' count '] = $this->db->count_all_results (', false);//Do not reset the query Builder  Array_push ($this, errors, $this->db->last_query ());  }//Paging data processing if (Isset ($page) && isset ($param [' limit ')]) {//Pagination boundary value setting $offset = $param [' page '] <= 1 ?      0: ($param [' page ']-1) * $param [' limit '];    $this->db->limit ($param [' limit '], $offset);        }//combination of collation if (!empty ($order) && Is_array ($order)) {foreach ($order as $key = = $val) {      $this->db->order_by ($key, $val);      }}else{//default follows the primary key of this table in reverse $primary = $this->getprimary ();      if (!empty ($primary)) {$this->db->order_by ($primary, ' DESC ');    }} $query = $this->db->get ();    Array_push ($this, errors, $this->db->last_query ());    $rs [' list '] = $query->result_array ();  return $rs; }/** * Parse parameter */Private function ParseParam ($param) {if (Isset ($param [' Compare '])} {foreach ($param [' compare ')    ] as $key = $val) {if (!empty ($val)) $this->db->where ($key, $val);  }} if (Isset ($param [' like ')}) {foreach ($param [' like '] as $key = + $val) {if (!empty ($val)) $this-&G      T;db->like ($key, $val); }} if (Isset ($param [')]) {foreach ($param [' in '] as $key = + $val) {if (!empty ($val)) $this->db-&      Gt;where_in ($key, $val);    }} if (Isset ($param [' customstr '])) {if (!empty ($val)) $this->db->where ($param [' customstr ']); }}/** * New information * @param string $table table name * @param array $param data variable * @return INT ID */Public Function Add (    $table = ", $param = Array ()) {if (empty ($table) | |!is_array ($param) | | empty ($PARAM)) {return FALSE;      }//Write Data table $this->db->insert ($table, $param);    Array_push ($this, errors, $this->db->last_query ());  Return record ID return $this->db->insert_id (); }/** * Update classification information * @param string $table table name * @param string $primary table primary KEY * @param int $id class ID * @par Am array $param updated data * @return Type  */Public Function update ($table = ', $primary = ', $id = 0, $param = Array ()) {if (empty ($table) | | empty ($prima RY) | | 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 (); }/** * Delete the specified ID record * @param string $table table name * @param string $primary table primary key * @param array $id category ID * @  return int */Public Function Delete ($table = ', $primary = ', $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 (); /** * Gets the primary key of the table * @param string $database database name * @param strting $table Table name */Public function GetprimaRy ($table = ", $database = self::d atabase) {if (empty ($database) | | empty ($table)) {return FALSE; } $sql = "Select K.column_name from information_schema.table_constraints t JOIN information_schema.key_co Lumn_usage k USING (constraint_name,table_schema,table_name) WHERE t.constraint_type= ' PRIMARY KEY ' A    ND t.table_schema= ' qndnew ' and t.table_name= ' Qnd_user ' ";    $query = $this->db->query ($sql)->result_array (); return Isset ($query [0][' column_name '])?  $query [0][' column_name ']: false; }/** * Debug SQL statement */Public Function Debugsql () {if (count ($this->errors) > 0) {foreach ($this->err      ORS as $val) {echo $val. ' <br> '; }    }  }}

The specific business logic model is as follows:

Class User_model extends My_model {  const User = ' Qnd_user ';  Public $selectFields = Array (    ' id ',    ' guid ', '    phone ',    ' userName ', '    password ',    ' Headportraits ',    ' nickname ',    ' createtime ',  );  Const Sms_role = ' qnd_role ';  Public function __construct ()  {  }}

The controller is tested as follows:

Public Function Modeltest () {    $this-load model (' User_model ');//loading model    $WHEREARR = Array (            ' C Ompare ' =>array (              ' userName ' = ' Frank ',            ),          );    $rs = Pagedata, User_model, $this (' User_model ', ' User ', $WHEREARR);    Print_r ($RS);    User_model, Debugsql, $this, ();  }

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.