CI 核心優勢在於**徹底的 MVC 分層**:Model 專司資料邏輯,Controller 專司流程控制,View 專司呈現。三層互不混雜,極大提升可維護性。
class User_model extends CI_Model {
public function __construct() { parent::__construct(); }
// 查詢:支援條件陣列,便於 Controller 組裝複雜查詢
public function userInfo($where = array()) {
if($where && is_array($where)) {
$res = $this->db->select('id, username, age')->where($where)->get('users');
} else {
$res = $this->db->select('id, username, age')->get('users');
}
return $res->result_array(); // 二維陣列
}
// 新增
public function userAdd($data) {
if($data && is_array($data)) {
return $this->db->insert('users', $data);
}
return false;
}
// 刪除
public function userDel($id) {
if($id) {
return $this->db->where('id', $id)->delete('users');
}
return false;
}
// 修改
public function userEdit($where, $data) {
if($where && is_array($where)) {
return $this->db->where($where)->update('users', $data);
}
return false;
}
// 聯表查詢範例
// $this->db->select('p.*, u.username')->from('payment p')->join('users u', 'p.uid = u.id')->order_by('p.id', 'desc')->get();
}
User_model,檔名小寫 user_model.phpCI_Model$this->load->model('User_model', 'user'); 別名 user$this->load->model('blog/User_model');application/config/autoload.php$this->load->model('User_model', '', TRUE); 第三參數 TRUEclass Users extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('User_model', 'user');
}
// 列表
public function index() {
$data['user_list'] = $this->user->userInfo();
$this->load->view('user_list', $data);
}
// 新增
public function user_add() {
$data = array(
'username' => $this->input->post('name'),
'age' => intval($this->input->post('age'))
);
$bool = $this->user->userAdd($data);
$this->show_tips($bool ? '操作成功!' : '操作失敗!');
}
// 修改
public function user_edit() {
$id = $this->input->post('id');
$data = array(
'username' => $this->input->post('name'),
'age' => intval($this->input->post('age'))
);
if($id) {
$bool = $this->user->userEdit(array('id'=>$id), $data);
$this->show_tips($bool ? '操作成功!' : '操作失敗!');
} else {
$this->show_tips('非法操作!');
}
}
// 刪除
public function user_del() {
$id = $this->input->post('id');
$bool = $this->user->userDel($id);
$this->show_tips($bool ? '操作成功!' : '操作失敗!');
}
}
users.php,類名首字母大寫 UsersCI_Controllerapplication/core/MY_Controller.php,定義前台/後台基類application/config/routes.php<?php $this->load->view('header'); ?>
<div>
<table>
<?php if($user_list): ?>
<?php foreach($user_list as $v): ?>
<tr><td><?=$v['username'];?></td></tr>
<?php endforeach; ?>
<?php endif; ?>
</table>
</div>
<?php $this->load->view('footer'); ?>
$data 變數short_open_tag,CI 也會自動解析 <?= ?>註:代碼為示意,可能存在手誤,請參考官方手冊修正後使用。更多實用用法請查閱 CI 使用手冊。
原文連結:https://www.cnblogs.com/farwish/p/3991419.html
作者:黑眼詩人 <www.chenwei.ws>