首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

CodeIgniter 常用開發技巧速查手冊

     編輯:PHP 綜合知識

一、視圖中載入靜態資源 (CSS/JS/圖片)

使用 base_url() 產生完整絕對路徑,避免相對路徑在不同層級 URL 失效:

<link rel="stylesheet" href="<?=base_url('assets/css/style.css')?>">
<link rel="stylesheet" href="<?=base_url('assets/js/kindeditor/themes/default/default.css')?>">
<link rel="shortcut icon" href="<?=base_url('assets/images/favicon.ico')?>">

<script src="<?=base_url('assets/js/jquery.min.js')?>"></script>
<script src="<?=base_url('assets/js/admin.public.js')?>"></script>
<script src="<?=base_url('assets/js/jquery.artDialog.js?skin=default')?>"></script>
<script src="<?=base_url('assets/js/datejs/WdatePicker.js')?>"></script>
<script src="<?=base_url('assets/js/kindeditor/kindeditor-min.js')?>"></script>

前置條件:config.php 設定 $config['base_url'],並載入 url_helper ($this->load->helper('url'); 或 autoload)。

二、視圖中嵌入子視圖 (模組化佈局)

<?php $this->load->view('partials/header'); ?>

<main>
    <!-- 主要內容 -->
</main>

<?php $this->load->view('partials/footer'); ?>

適用於 Header、Footer、Sidebar、Widget 等跨頁面共用區塊。

三、視圖中直接使用 PHP 函數

視圖檔案本質是 PHP 腳本,可直接呼叫任何 PHP 內建函數或自訂 Helper 函數:

<p>文章發布時間:<?=date('Y-m-d H:i', $article['created_at'])?></p>
<p>內容摘要:<?=character_limiter($article['content'], 200)?></p>
<!-- character_limiter 來自 text_helper -->

四、模型中獲取 CI 超級物件 (跨模型/庫調用)

class MyModel extends CI_Model {
    public function someMethod() {
        $CI =& get_instance(); // 取得 CI 控制器實例引用
        $CI->load->model('Other_model');
        $CI->load->library('session');
        $data = $CI->other_model->getData();
        $CI->session->set_userdata('key', $value);
    }
}

注意:模型建構子已自動載入資料庫,一般情況下直接用 $this->db 即可,無需 get_instance()。

五、常用 Helper 載入 (建議 autoload)

// config/autoload.php
$autoload['helper'] = ['url', 'form', 'text', 'date', 'file', 'html', 'security'];

六、資料庫操作速查

操作代碼
插入$this->db->insert('table', $data); / $id = $this->db->insert_id();
批次插入$this->db->insert_batch('table', $dataArray);
更新$this->db->where('id', $id)->update('table', $data);
刪除$this->db->where('id', $id)->delete('table');
單筆查詢$row = $this->db->get_where('table', ['id' => $id])->row_array();
多筆查詢$rows = $this->db->get('table')->result_array();
自定 SQL$this->db->query('SELECT * FROM table WHERE id = ?', [$id])->result_array();
事務$this->db->trans_start(); ... $this->db->trans_complete();

七、輸出與重導向

// JSON 回應 (API)
$this->output->set_content_type('application/json')->set_output(json_encode($data));

// 重導向
redirect('controller/method', 'refresh'); // 或 'location'

// 設定 HTTP 狀態碼
$this->output->set_status_header(404);

八、Session 閃存訊息 (一次性提示)

// 設定
$this->session->set_flashdata('success', '操作成功!');
$this->session->set_flashdata('error', '操作失敗:' . $msg);

// 視圖中顯示
<?php if ($this->session->flashdata('success')): ?>
    <div class="alert alert-success"><?=$this->session->flashdata('success')?></div>
<?php endif; ?>

九、表單驗證

$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');

if ($this->form_validation->run() === FALSE) {
    $this->load->view('register_form');
} else {
    // 成功邏輯
}

十、檔案上傳

$config = [
    'upload_path' => FCPATH . 'uploads/',
    'allowed_types' => 'jpg|png|gif|pdf',
    'max_size' => 2048, // KB
    'encrypt_name' => true,
];
$this->load->library('upload', $config);
if ($this->upload->do_upload('file_field')) {
    $info = $this->upload->data();
    // $info['file_name'], $info['full_path'], ...
} else {
    $error = $this->upload->display_errors();
}

總結

掌握以上十大類常用技巧,覆蓋 CodeIgniter 開發 90% 的日常場景。建議將常用片段存為 IDE Live Templates / Snippets,進一步提升編碼速度。遇到未列場景,優先查閱官方用戶指南對應類別章節 (Database, Session, Upload, Email, Image, Pagination, Encryption 等)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved