CI框架(CodeIgniter)公共模型類定義與用法示例
本文實(shí)例講述了CI框架(CodeIgniter)公共模型類定義與用法。分享給大家供大家參考,具體如下:
我們都知道,操作數(shù)據(jù)庫(kù)的方法都寫在模型中。但是一般情況下,一張表往往至少對(duì)應(yīng)4個(gè)操作,也就是所謂crud。那么如果20張表,所對(duì)應(yīng)的模型方法,就達(dá)到了80個(gè),重復(fù)的操作顯然這已經(jīng)是一個(gè)體力活兒。
那么就對(duì)單表操作時(shí),我們進(jìn)行一下簡(jiǎn)單的封裝。如下是ci框架的示例:
<?php
/**
* Created by PhpStorm.
* User: kangjianrong
* Date: 16-8-26
* Time: 上午10:29
*/
class My_model extends CI_Model {
//數(shù)據(jù)庫(kù)
public $errors = array();
const dataBase = 'qndnew';
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
/**
* 查詢分頁(yè)數(shù)據(jù)(使用于簡(jiǎn)單的單表操作)
* @param string $model 模型 例如:User_model
* @param string $table 表名
* @param string $select_fields 要顯示字段
* @param array $param 查詢條件:
* compare(比較):
* array($key => $val) $key為要操作的字段,$val為要操作的值
* array('name !=' => $name, 'id <' => $id, 'date >' => $date);
* like(模糊查詢)
* array('title' => $match, 'page1' => $match, 'page2' => $match)
* customStr(自定義字符串):
* "name='Joe' AND status='boss' OR status='active'"
* in:
* array('userName' => array('Frank', 'Todd', 'James'))
* @param string $page 當(dāng)前頁(yè)數(shù)(查詢?nèi)繑?shù)據(jù)時(shí),設(shè)置為空)
* @param string $limit 查詢條數(shù)(查詢?nèi)繑?shù)據(jù)時(shí),設(shè)置為空)
* @param array $order 排序條件:
* array($key => $val)
* $key為排序依據(jù)的字段,
* $val為排序的方式【asc (升序,默認(rèn))或 desc(降序), 或 random(隨機(jī))】
* @$isReturnCount boole 是否返回總條數(shù)
* @return array|boolean
*
*/
public function pageData($model, $table, $param = array(),$select_fields = '', $page = '1', $limit = '15', $order = array(),$isReturnCount = true){
if(empty($model) || empty($table)){
return false;
}
$this -> load -> model($model);
$table = $this->db->dbprefix.$table;
//處理查詢字段
if(!empty($select_fields)){
$this->db->select($select_fields)->from($table);
}elseif(isset($this -> $model -> selectFields)){
$this->db->select($this -> $model -> selectFields)->from($table);
}else{
$this->db->select('*')->from($table);
}
//處理查詢條件
if (is_array($param) && count($param) > 0){
$this -> parseParam($param);
}
//統(tǒng)計(jì)總數(shù)
if($isReturnCount){
$rs['count'] = $this->db->count_all_results('',false);//不重置查詢構(gòu)造器
array_push($this -> errors,$this->db->last_query());
}
//分頁(yè)數(shù)據(jù)處理
if(isset($page) && isset($param['limit'])){
//分頁(yè)邊界值 設(shè)置
$offset = $param['page'] <= 1 ? 0 : ($param['page']-1) * $param['limit'];
$this->db->limit($param['limit'], $offset);
}
//排序規(guī)則的組合
if (!empty($order) && is_array($order))
{
foreach ($order as $key => $val)
{
$this->db->order_by($key, $val);
}
}else{
//默認(rèn)按照此表的主鍵倒序
$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;
}
/**
* 解析參數(shù)
*/
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->db->like($key, $val);
}
}
if(isset($param['in'])){
foreach ($param['in'] as $key => $val){
if (!empty($val)) $this->db->where_in($key, $val);
}
}
if(isset($param['customStr'])){
if (!empty($val)) $this->db->where($param['customStr']);
}
}
/**
* 新增信息
* @param string $table 表名稱
* @param array $param 數(shù)據(jù)變量
* @return INT ID
*/
public function add($table = '', $param = array())
{
if(empty($table) || !is_array($param) || empty ($param)){
return FALSE;
}
//寫入數(shù)據(jù)表
$this->db->insert($table, $param);
array_push($this -> errors,$this->db->last_query());
//返回記錄ID
return $this->db->insert_id();
}
/**
* 更新分類信息
* @param string $table 表名稱
* @param string $primary 表主鍵
* @param int $id 分類ID
* @param array $param 更新的數(shù)據(jù)
* @return type
*/
public function update($table = '', $primary = '', $id = 0, $param = array())
{
if(empty($table) || empty($primary) || 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();
}
/**
* 刪除指定ID記錄
* @param string $table 表名稱
* @param string $primary 表主鍵
* @param array $id 分類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();
}
/**
* 獲取表的主鍵
* @param string $database 數(shù)據(jù)庫(kù)名稱
* @param strting $table 表名稱
*/
public function getPrimary($table = '', $database = self::dataBase)
{
if(empty($database) || empty($table))
{
return FALSE;
}
$sql = "SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING (constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
AND 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語(yǔ)句
*/
public function debugSql(){
if(count($this->errors) > 0){
foreach($this->errors as $val){
echo $val.'<br>';
}
}
}
}
具體的業(yè)務(wù)邏輯模型如下:
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()
{
}
}
控制器中測(cè)試如下:
public function modelTest(){
$this -> load -> model('User_model'); // 載入 model
$whereArr = array(
'compare'=>array(
'userName' => 'Frank',
),
);
$rs = $this -> User_model -> pageData('User_model','user',$whereArr);
print_r($rs);
$this -> User_model -> debugSql();
}
更多關(guān)于CodeIgniter相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《codeigniter入門教程》、《CI(CodeIgniter)框架進(jìn)階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《ThinkPHP入門教程》、《ThinkPHP常用方法總結(jié)》、《Zend FrameWork框架入門教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家基于CodeIgniter框架的PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
Ubuntu VPS中wordpress網(wǎng)站打開時(shí)提示”建立數(shù)據(jù)庫(kù)連接錯(cuò)誤”的解決辦法
這篇文章給大家介紹的是在Ubuntu VPS中wordpress網(wǎng)站打開時(shí)提示”建立數(shù)據(jù)庫(kù)連接錯(cuò)誤”的解決辦法,相信"建立數(shù)據(jù)庫(kù)連接錯(cuò)誤"大家并不陌生,最近我在做一個(gè)項(xiàng)目的時(shí)候就又遇到了這個(gè)問(wèn)題,現(xiàn)在將我解決的步驟分享給大家,希望對(duì)同樣遇到這個(gè)問(wèn)題的朋友們能有所幫助。2016-11-11
eWebEditor v3.8 商業(yè)完整版 (PHP)
eWebEditor v3.8 商業(yè)完整版 (PHP)...2006-12-12
PHP 動(dòng)態(tài)生成靜態(tài)HTML頁(yè)面示例代碼
這篇文章主要為大家分享下PHP 動(dòng)態(tài)生成靜態(tài)HTML頁(yè)面示例代碼,需要的朋友可以參考下2014-01-01
PHP curl偽造IP地址和header信息代碼實(shí)例
這篇文章主要介紹了PHP curl偽造IP地址和header信息代碼實(shí)例,本文給出服務(wù)器端和客戶端實(shí)現(xiàn)代碼,提供偽造功能和服務(wù)器端檢測(cè)代碼,需要的朋友可以參考下2015-04-04
php根據(jù)isbn書號(hào)查詢amazon網(wǎng)站上的圖書信息的示例
這篇文章主要介紹了php根據(jù)isbn書號(hào)查詢amazon網(wǎng)站上的圖書信息的示例,需要的朋友可以參考下2014-02-02
ThinkPHP框架實(shí)現(xiàn)的微信支付接口開發(fā)完整示例
這篇文章主要介紹了ThinkPHP框架實(shí)現(xiàn)的微信支付接口開發(fā),結(jié)合完整實(shí)例形式詳細(xì)分析了基于thinkPHP框架的微信支付接口操作步驟、實(shí)現(xiàn)技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-04-04
使用php發(fā)送有附件的電子郵件-(PHPMailer使用的實(shí)例分析)
本篇文章介紹了使用php發(fā)送有附件的電子郵件-(PHPMailer使用的實(shí)例分析)需要的朋友參考下2013-04-04

