@update 2016-4-2 13:45:35
CI版本:3.0.0
一、目錄結構
ci_demo
├─myapp 應用主目錄
│ ├─autoload.php 自定義的自動加載文件(可選)
│ ├─myapp.php應用入口文件,拷貝index.php得到,注意修改$application_folder = 'myapp';
│ ├─cache 緩存目錄
│ ├─config 配置目錄,包括autoload,database,routes等
│ ├─controllers 控制器目錄,可以分為api和web部分(命名自定義),也可以不分
│ │ ├─api api相關的控制器類
│ │ └─web
│ ├─core 如果在config.php里配置`$config['subclass_prefix'] = 'BASE_'`,則對應的類文件在此,如Base_Controller.php
│ ├─helpers 自定義幫助類
│ ├─hooks 自定義鈎子類
│ ├─language
│ ├─libraries 自定義類庫
│ ├─logs
│ ├─models 模型類,文件名小寫
│ ├─third_party
│ └─views 視圖類,可以包含子文件夾,建議與控制器類文件夾對應
│ └─user
├─common 公共文件目錄,包括靜態文件、自定義類庫
│ ├─css
│ ├─images
│ ├─img
│ │ └─report
│ ├─js
│ └─lib 第三方類庫可以放這里
└─system CI框架核心文件
├─core
│ └─compat
├─database
│ └─drivers
│ ├─cubrid
│ ├─ibase
│ ├─mssql
│ ├─mysql
│ ├─mysqli
│ ├─oci8
│ ├─odbc
│ ├─pdo
│ ├─postgre
│ ├─sqlite
│ ├─sqlite3
│ └─sqlsrv
├─fonts
├─helpers
├─language
└─libraries
多個app可以建立多個目錄,可以有多個入口文件。
CI3.0支持composer,在最外層可以有vendor目錄。
二、控制器
位於application/controllers:
命名規則
1.文件名必須是大寫字母開頭
2.類名必須以大寫字母開頭
3.文件名與類名名稱一致
4.url里類名可以是小寫
例如User.php,類名是User。
示例
myapp/controllers/Welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');
}
}
application/controllers下可以有子目錄(可以嵌套多層,不建議)。例如:
application/controllers/api/。訪問的時候記得在url里拼上api。
http://localhost/ci/myapp.php/Welcome
http://localhost/ci/myapp.php/api/Test
提示:
如果發現提示404,那么可能是不支持這樣的url方式,請使用原始的:
http://localhost/ci/myapp.php?Welcome
http://localhost/ci/myapp.php?c=api&m=Test
或者嘗試rewrite。如linux下nginx配置:
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?/$1 last;
break;
}
框架自動將url中類的名稱首字母大寫(core/CodeIgniter.php 406行):
$class = ucfirst($RTR->class);
require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php');
所以,這樣的url也是可以的:
http://localhost/ci/myapp.php/welcome
http://localhost/ci/myapp.php/api/test
父控制器
默認的,父控制器是CI_Controller。建議重新新建個父控制器,例如BASE_Controller,繼承自CI_Controller。
常用函數
site_url('stu/index') 不能傳參數,例如生成:
http://localhost/dada/admin-ci/index.php/stu/index
base_url() 獲取應用所在根目錄url地址,例如http://localhost/dada/admin-ci/,去掉了入口文件
config_item('item_key') 獲取配置值。建議使用配置類訪問這些信息:
$this->config->load('filename');
$this->config->item('item name');
更多函數:
current_url() 當前url
redirect() 重定向
log_message() 打印日志
注意:
site_url()依賴url類,需要在autoload.php自動加載下:$autoload['helper'] = array('url');
默認控制器
打開 application/config/routes.php 文件來設置默認控制器:
$route['default_controller'] = 'Blog';
_remap()
如果控制器里存在這個方法,URI里的方法(METHOD)就會被替換成_remap方法,但同時接收URI里的方法參數,供后續使用。
if (method_exists($class, '_remap'))
{
$params = array($method, array_slice($URI->rsegments, 2));
$method = '_remap';
}
_remap會廢除掉由 URI 片段來決定哪個方法被調用的規則,允許你重新定義調用方法的規則(方法的路由規則)。
那么我們就可以在根控制器里(例如BASE_Controller)使用這個_remap()方法,進行數據的統一收集、輸出。
示例:core/BASE_Controller.php
class Web_Controller extends CI_Controller{
public function _remap($method, $params = array()){
if (!method_exists($this, $method)) {
$this->showError('您訪問的頁面不存在!');
}
//重新接收URI里待訪問的方法
$data = call_user_func_array(array($this, $method), $params);
}
}
當然,也可以進行異常捕獲等其他功能。下面是API_Controller里的_remap方法,實現了統一接收參數,統一返回json數據。
class API_Controller extends CI_Controller{
public function _remap($method, $params = array())
{
try {
if (!method_exists($this, $method)) {
throw new HException(ErrorInfo::$err_bad_request);
}
$data = call_user_func_array(array($this, $method), $params);
$succ_info = ErrorInfo::$succ;
$result['ecd'] = $succ_info['code'];
$result['msg'] = $succ_info['msg'];
$result['locate'] = $this->_locate;
$result['result'] = $data;
} catch (HException $e) {
$result['ecd'] = $e->getCode();
$result['msg'] = $e->getMessage();
$result['locate'] = $this->_locate;
$result['result'] = $e->getData();
} catch (Exception $e) {
$result['ecd'] = $e->getCode();
$result['msg'] = $e->getMessage();
$result['locate'] = $this->_locate;
$result['result'] = '';
}
if (!empty($e) || $this->_debug) {
// var_dump($e);
}
if (is_object($result['result'])) {
$result['result'] = obj2arr($result['result']);
}
if (empty($result['result'])) {
unset($result['result']);
}
echo json_encode($result);
exit;
}
}
自動加載的父類
默認子類的前綴是CI_,那么會自動加載application/core/CI_Controller.php(core/CodeIgniter.php 369行):
if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'))
{
require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php';
}
// Add
if (file_exists(BASEPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'))
{
require_once BASEPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php';
}
// End
通過 URI 分段向你的方法傳遞參數
如果你的 URI 多於兩個段,多余的段將作為參數傳遞到你的方法中。
例如,假設你的 URI 是這樣:
example.com/index.php/products/shoes/sandals/123
你的方法將會收到第三段和第四段兩個參數("sandals" 和 "123"):
<?php
class Products extends CI_Controller {
public function shoes($sandals, $id)
{
echo $sandals;
echo $id;
}
}
三、路由
pathinfo模式
支持http://52fhy.com/test.php/stu/one1/4 支持純值的方式
支持http://52fhy.com/test.php/stu/one?uid=2
不支持http://52fhy.com/test.php/stu/one/uid/2 不支持參數是鍵值對的形式
路由配置參見config/routes.php
簡單路由示例
$route['default_controller'] = 'Test/index'; //默認訪問的方法
$route['act_1'] = 'Activity/one'; //前面為自定義的url,后面為實際url
四、配置
入口文件也配置部分參數,例如改應用路徑。
常用配置文件:
config.php需要改入庫文件名
autoload.php自動加載配置
database.php配置數據庫
routes.php路由配置文件
memcached.php緩存配置
當然可以自己新建配置文件。
小技巧:
在config.php里配置
$config['subclass_prefix'] = 'BASE_';
那么應用里core里以BASE_開頭的類會被自動加載,且controllers或者models里面的類必須繼承自core里的類。
config.php常見配置:
//自定義core類前綴
$config['subclass_prefix'] = 'BASE_';
//url正則配置,如果不正確,改成如下:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-,';
//cookie配置
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
$config['global_xss_filtering'] = FALSE;
autoload.php常見配置:
//使用session庫
$autoload['libraries'] = array('session');
//自動加載helper類
$autoload['helper'] = array('url', 'file', 'string', 'date');
五、模型
所在目錄
默認是在APPPATH/models。在core/Loader/php里:
/**
* List of paths to load libraries from
*
* @var array
*/
protected $_ci_library_paths = array(APPPATH, BASEPATH);
/**
* List of paths to load models from
*
* @var array
*/
protected $_ci_model_paths = array(API_MODEL, ADMIN_MODEL, APPPATH);
/**
* List of paths to load helpers from
*
* @var array
*/
protected $_ci_helper_paths = array(APPPATH, BASEPATH);
按照上面的定義,可以自定義。在一個大項目包含多個子項目時,一般model是通用的,那么最好一個公共的位置,例如:common/models。
命名規則
默認的規則是:
文件名全部小寫,例如user_model.php,類名首字母大寫:User_model
載入模型:$this->load->model('User_model');第二個參數是別名
使用模型:$data = $this->User_model->getAll();
如果想使用駝峰命名規則:(推薦)
例如:UserModel.php
$this->UserModel->getById();
則需要對system/core/Loader.php里的model()方法進行修改:屏蔽掉
$model = ucfirst(strtolower($model));
就可以保持類名和文件名大小寫一致了。下面的示例假設Modle都已經更改為駝峰命名了。
如何使用模型
方式一:控制器直接使用
示例:myapp/controllers/Welcome.php
public function t() {
//載入模型
$this->load->database();
//獲取articles表里的所有數據並以數組形式返回
return $this->db->get('articles')->result_array();
}
默認如果未全局加載database類,需要$this->load->database();
如果您需要一個在整個項目中都起作用的特定模型,您可以讓CI在初始化時自動裝載它。實現的方法是打開 application/config/autoload.php 文件,然后在自動裝載數組中添加上這個模型。
$autoload['libraries'] = array('database');
方式二:間接使用模型文件
上面訪問數據是最簡單的了,不需要建立任何模型文件。但這種方法不推薦使用,不符合MVC模式。
現在我們通過建立模型文件,在控制器里間接使用。
1、建立模型
示例:myapp/models/UserModel.php
class UserModel extends CI_Model{
function get_last_user()
{
$query = $this->db->get('user', 10); //user表
return $query->result();
}
}
2、控制器里使用
在控制器里加載並使用:
$this->load->model('UserModel');
$this->UserModel->get_last_user();
方式三:優化模型
但感覺還是不方便。原因:
1、到處在使用$this->db不方便維護;
2、不推薦直接繼承CI_Model。
下面我們進行優化:
1、重寫自己的父Model
core/Model.php
可以看到,模型的基類是CI_Model,建議重新建立個父類Model繼承CI_Model。
這里我們建立了API_Model繼承CI_Model。並添加一些公用的方法。
示例:
class API_Model extends CI_Model
{
protected $table;
protected static $db = null;
protected static $db_name = null;
protected $_create_time = true;
protected $_update_time = true;
protected $_id = true;
public function add($data)
{
if($this->_create_time){
$data['create_time'] = now();
}
if($this->_update_time){
$data['update_time'] = now();
}
$db = $this->getDBHanlder();
$db->insert($this->table, $data);
$id = $db->insert_id();
if ($id && $this->_id) {
return $this->getById($id);
}
return (object)$data;
}
public function updateById($id, $data)
{
$db = $this->getDBHanlder(Enum_DB_Name::MASTER);
return $db->where(array('id' => $id))->update($this->table, $data);
}
public function updateByParams($where, $data)
{
$db = $this->getDBHanlder(Enum_DB_Name::MASTER);
$this->bulidWhere($where, $db);
return $db->update($this->table, $data);
}
public function deleteByParams($where)
{
$db = $this->getDBHanlder(Enum_DB_Name::MASTER);
$this->bulidWhere($where, $db);
return $db->delete($this->table);
}
public function getById($id)
{
if (empty($id)) return array();
return $this->getDBHanlder(Enum_DB_Name::SLAVE)->get_where($this->table, array('id' => $id))->row();
}
/**
* @param array $where
* @param array $order($orderby, $direction = '')
*/
public function getByParams($where = array(), $orders = array(), $offset = NULL , $limit = NULL)
{
$db = $this->getDBHanlder(Enum_DB_Name::SLAVE);
$this->bulidWhere($where, $db);
if($orders) $db->order_by($orders[0], $orders[1]);
return $db->get($this->table, $limit, $offset)->row();
}
/**
* @param array $where
* @param array $order($orderby, $direction = '')
*/
public function listByParams($where = array(), $orders = array(), $offset = NULL , $limit = NULL)
{
$db = $this->getDBHanlder(Enum_DB_Name::SLAVE);
$this->bulidWhere($where, $db);
if($orders) $db->order_by($orders[0], $orders[1]);
return $db->get($this->table, $limit, $offset)->result();
}
public function getCountByParams($where = array())
{
$db = $this->getDBHanlder(Enum_DB_Name::SLAVE);
$this->bulidWhere($where, $db);
return $db->count_all_results($this->table);
}
/**
* Execute the query, return row object
* @param string $sql
* @param array $binds = FALSE An array of binding data
* @param bool $return_object = FALSE
* @return mixed
*/
public function query($sql, $binds = FALSE, $return_array = FALSE){
if($return_array){
return $this->getDBHanlder(Enum_DB_Name::SLAVE)
->query($sql, $binds)
->row_array();
}else{
return $this->getDBHanlder(Enum_DB_Name::SLAVE)
->query($sql, $binds)
->row();
}
}
/**
* Execute the query, return rows object
* @param string $sql
* @param array $binds = FALSE An array of binding data
* @param bool $return_object = FALSE
* @return mixed
*/
public function querys($sql, $binds = FALSE, $return_array = FALSE){
if($return_array){
return $this->getDBHanlder(Enum_DB_Name::SLAVE)
->query($sql, $binds)
->result_array();
}else{
return $this->getDBHanlder(Enum_DB_Name::SLAVE)
->query($sql, $binds)
->result();
}
}
/**
* 獲取數據庫對象
*/
public function getDBHanlder($db_name = Enum_DB_Name::MASTER)
{
if(is_null(self::$db)
){
self::$db = $this->load->database($db_name, true);
}
return self::$db;
}
/**
* 解析where
* 支持:普通鍵值對參數、k__in, k__nin查詢
*/
protected function bulidWhere($where, &$db) {
if($where){
foreach($where as $k=>$v){
if(strpos($k, '__')){
$temp = explode('__', $k);
if($temp[1] == 'in'){
$db->where_in($temp[0] ,$v);
}
if($temp[1] == 'nin'){
$db->where_not_in($temp[0] ,$v);
}
if($temp[1] == 'like'){
$db->like($temp[0] ,$v, 'both');
}
if($temp[1] == 'llike'){
$db->like($temp[0] ,$v, 'before');
}
if($temp[1] == 'rlike'){
$db->like($temp[0] ,$v, 'after');
}
unset($where[$k]);
}
}
$db->where($where);
}
}
}
其中:
abstract class Enum_DB_Name
{
const MASTER = 'master';
const SLAVE = 'slave';
}
2、建立子模型
示例:myapp/models/UserModel.php
class UserModel extends API_Model{
protected $table = 'user';
function get_last_user(){
$query = $this->listByParams(array(
'flag' => 1
),array('id','desc'), 0 , 10);
return $query;
}
function getUser($uid){
$query = $this->getById($uid);
return $query;
}
function updUser($uid, $data){
$this->updateById($uid, $data);
}
function addUser($data){
$this->add($data);
}
function delUser($uid){
$this->deleteByParams(array('id' => $uid));
}
}
是不是發現使用的時候簡單多了?不用總是寫表名,不用總是$this->db。當然,上面的API_Model不是最終的,大家可以自行優化。
3、控制器里使用
與方式二相同。
數據庫操作
下面提供了常見的數據庫的CURD操作示例:
增 $this->db->insert('user', $data);
$insert_id = $this->db->insert_id();
刪 $this->db->delete('user', array('id' => $uid));
查 $this->db->get('user')->result_array();
$this->db->get_where('user', array('id'=> $uid))->row_array();
普通查詢 :query() 函數以object(對象)的形式返回一個數據庫結果集.
$querys = $this->db->query('select * from user'); //返回結果集,與get()或者get_where()一致,等同於
$querys = $this->db->get('user');
$this->db->select();
$this->db->select('id,name')->get('user'); //支持選擇查詢字段,可以連貫查詢
$data = $this
->where(array('uids !=' => $uid))
->where_in('flag', $flag_map)
->like('gps_geo', substr($geo, 0, 4), 'after')
->order_by('book_time', 'desc')
->limit(10, 0)
->get($this->table)
->result_array();
$this->db->where();
$querys = $this->db->select('id,name')->where('id !=', 1)->get('user');
注意運算符,與ThinkPHP不一樣。不管是數組還是鍵值對,條件都寫在鍵里,使用!=,>=等
更多:
$this->db->or_where();本函數與上面的那個幾乎完全相同,唯一的區別是本函數生成的子句是用 OR 來連接的:
$this->db->where_in();生成一段 WHERE field IN ('item', 'item') 查詢語句,如果合適的話,用 AND 連接起來。
$this->db->or_where_in();
$this->db->where_not_in();
$this->db->or_where_not_in();
$this->db->like('title', 'match');
$this->db->or_like();
$this->db->not_like();
$this->db->or_not_like();
$this->db->group_by();
$this->db->distinct();
$this->db->having();
$this->db->order_by();
$this->db->limit();
$this->db->where()->count_all_results();
獲得某個特定的Active Record查詢所返回的結果數量,與$this->db->count_all('stu');不同
查詢輔助函數:
$this->db->insert_id() 新增字段Id
$this->db->affected_rows() 當執行寫入操作(insert,update等)的查詢后,顯示被影響的行數。
$this->db->count_all('stu') 計算出指定表的總行數並返回。實際:SELECT COUNT(*) AS `numrows` FROM `stu`
$this->db->last_query() 返回最后運行的查詢語句
結果集方法:
num_rows()記錄數統計
row()單行數據,對象格式
result()全部數據,對象格式
row_array()單行數據,數組格式
result_array()全部數據,數組格式
封裝查詢
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
改 $this->db->update('user', $data, array('id' => $uid));
事務
自動事務
傳統上, 事務需要實現大量工作, 他們要求你隨時跟蹤你的查詢, 並根據查詢的成功或失敗來決定 提交 還是 回滾。這是特別麻煩的嵌套查詢。相比之下, 我們實現了一種智能的事務系統, 它將自動地為你做這些事情(如果你選擇手動管理你的事務, 這也是可以的, 但這確實沒什么好處)。
要使用事務來運行你的查詢, 你可以使用如下所述的 $this->db->trans_start() 和 $this->db->trans_complete() 函數:
$this->db->trans_start();
$this->db->query('一條SQL查詢...');
$this->db->query('另一條查詢...');
$this->db->query('還有一條查詢...');
$this->db->trans_complete();
在 start/complete 函數之間, 你想運行多少條查詢都可以, 根據任何給定查詢的成功或失敗, 它們將被提交或者回滾。
手動運行事務
$this->db->trans_begin();
try{
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_commit();
}catch(Exception $e){
$this->db->trans_rollback();
}
說明: 手動運行事務時, 請務必使用
$this->db->trans_begin()函數, 而不是$this->db->trans_start().
六、視圖
使用方法:
$this->load->vars("list",$data);//不使用模板引擎,ci默認分配變量方式
$this->load->view("index"); //可以包含子目錄
建議抽出頁面的公共部分,例如header、footer。然后在頁面直接引入就可以了。
<?php include_once VIEWPATH . '/header.php' ?>
七、系統類庫及函數調用
1. 載入類庫
加載系統類庫:
$this->load->library('className'); //使用system/libraries文件夾類庫
$this->load->library(array('email', 'table')); //多個類庫可以通過傳遞包含類庫的數組一次加載
$this->className->func(); //直接調用加載類的方法
如果加載類庫時指定了第二個參數,則:
$this->load->library('className', 'myClass');
$this->myClass->func();
加載自定義類庫:
同樣使用$this->load->library()加載。
一般位於application/libraries文件夾下。如果與系統類重名,將覆蓋系統類(除了數據庫類無法被擴展或替換,剩余其他類均可)。
命名規則:
文件名首字母大寫. 例如: Myclass.php
類聲明首字母大寫. 例如: class Myclass
類的名字和文件名應相同.
可以擴展現有類:
新擴展的類所在的文件必須以 MY_ 為前綴(這個選項是可配置的).擴展的類必須繼承父類.
2. 載入輔助函數
$this->load->helper('name');
$this->load->helper( array('helper1', 'helper2', 'helper3') ); //同時載入多個
輔助函數文件一般保存在 system/helpers 或 application/helpers 文件夾中。CodeIgniter 將會先在 application/helpers 尋找對應的輔助函數文件, 如果目錄不存在或者目錄下沒有對應的輔助函數文件,CI 才會載入 system/helpers 下的輔助函數文件。與$this->load->library()載入規則相同。
3. 載入模型
$this->load->model('Model_name');
如果模型文件在子文件夾下,引用的時候要帶上相對路徑名,示例:
$this->load->model('blog/queries');
模型一旦被載入,你就能通過下面的方法使用它:
$this->Model_name->function();
4. 載入視圖
$this->load->view('name');
$this->load->view('name',$data); //同時賦予數據
$buffer = $this->load->view('blogview', $data, true); //不輸出而是返回數據
5. 載入配置文件
$this->config->load('filename');
$this->config->load('blog_settings', TRUE); //重復時合並
從配置文件中檢索元素,使用下面的函數:
$this->config->item('itemName');
動態設置/改變一個現有的配置元素:
$this->config->set_item('item_name', 'item_value');
自動加載:
要自動加載配置,請打開文件 autoload.php,它在 application/config/autoload.php,然后按照文件中的提示增加你想要自動加載的配置文件。
八、其它
將Session數據存入數據庫
由於Session數據數組是附帶一個Session ID保存在用戶cookie里的,你無法驗證它,除非你把session數據存儲在數據庫中。在一些不需要或很少需要安全保護的應用中,session ID 或許並不需要。
但如果你的應用需要安全保護,驗證是必須的。否則,用戶可以通過篡改Cookies來恢復舊的Session。
當session 數據在數據庫中可用時,每當從用戶cookie中發現一個有效的session,一個數據庫查詢就會被執行以匹配它。如果 session ID 不相配,session 就會被銷毀。Session ID永遠不會更新,它們只會在一個新的會話創建時生成。
為了存儲session,你必須先創建一個數據表。這是 session 類所需的基本結構(用於MySQL的):
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text DEFAULT '' NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);
注意: 默認情況下這個表叫做 ci_sessions。可以更改:
myapp/config/config.php
//session
//開啟seesion存儲到數據庫的時候需要配置
$config['sess_driver'] = 'database'; //開啟database驅動
$config['sess_cookie_name'] = 'qy-sessions';
$config['sess_expiration'] = 60 * 60 * 24 * 365;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = FALSE;
$config['sess_time_to_update'] = 300;
這樣就可以使用$this->session操作session了,會存儲到數據庫。
//設置seesion
$this->session->set_userdata($array);
//獲取session
$this->session->userdata('item');
//刪除session
$this->session->unset_userdata('some_name');
CI框架中site_url()的原理
var_dump($_SERVER['HTTP_HOST']);
var_dump($_SERVER['SCRIPT_NAME']);
var_dump($_SERVER['SCRIPT_FILENAME']);
var_dump(basename($_SERVER['SCRIPT_FILENAME']));
string 'localhost' (length=9)
string '/dada/admin-ci/test.php' (length=23)
string 'D:/phpsetup/www/htdocs/dada/admin-ci/test.php' (length=45)
string 'test.php' (length=8)
$base_url = (is_https() ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST']
.substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME'])));
//http://localhost/dada/admin-ci/
區塊注釋
@deprecated 3.0.0 廢棄方法
zend編輯器識別超級類方法
在父級控制器里加上
/**
* @property CI_Loader $load
* @property CI_DB_query_builder $db
* @property CI_Calendar $calendar
* @property CI_Email $email
* @property CI_Encrypt $encrypt
* @property CI_Ftp $ftp
* @property CI_Hooks $hooks
* @property CI_Image_lib $image_lib
* @property CI_Input $input
* @property CI_Language $language
* @property CI_Log $log
* @property CI_Output $output
* @property CI_Session $session
* @property CI_Upload $upload
* @property CI_URI $uri
* @property CI_Config $config
*/
與ThinkPHP比較
1、限制少,編碼自由;
2、適合寫API;
3、視圖較TP功能弱些,少了很多常量,模板標簽基本沒有;
4、控制器層少了很多方便的函數,如U(),$this->success(),少了很多常量,如CONTROLLER。實際開發可以自行定義。
5、模型操作比較麻煩,沒有D()方法,全局使用$this->db,實例化比較麻煩;每次數據操作需要帶表名(可優化);不能獲取表名和主鍵ID
隱藏入口文件
nginx
需要在vhost文件里添加rewrite
location / {
if (!-e $request_filename) {
rewrite ^/(.*)$ /app.php?/$1 last;
break;
}
}
為了多應用能正常訪問,如果入口文件為app.php,那么
index app.php
以及location ~ .*\.(php|php5)?$里
fastcgi_index app.php;
get_instance()
獲取CodeIgniter的一個實例,訪問CodeIgniter的原始資源。這個函數返回一個超級對象,這樣可以訪問model等資源。
在控制器里,直接使用$this引用CI的這個超級對象。當你在自定義類中想使用CodeIgniter原始類時,你可以這樣做:
首先,定義CodeIgniter對象賦給一個變量:
$CI =& get_instance();
一旦定義某個對象為一個變量,你就可以使用那個變量名 取代 $this:
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
//etc.
function addUserFav($uid,$type,$iid){
$ci = & get_instance();
$ci->load->model('UserFavModel');
$ci->UserFavModel->addFav($uid,$type,$iid);
}
參考:
CodeIgniter用戶指南:http://codeigniter.org.cn/user_guide/index.html
