在codeigniter(以下簡(jiǎn)寫(xiě)為ci)的上面一篇文章中,寫(xiě)了ci的基本構(gòu)架,本文章對(duì)新建一個(gè)頁(yè)面以及程序如何訪問(wèn)進(jìn)行探索,并實(shí)際操作實(shí)例。
在ci的訪問(wèn)是通過(guò)index.php訪問(wèn),后面可以跟mvc架構(gòu)中的c然后找到m 然后通過(guò)v進(jìn)行輸出。
1.先看訪問(wèn),ci的訪問(wèn)的是index.php 也就是入口。
2.然后進(jìn)入路由頁(yè)面進(jìn)行路由判斷,路由頁(yè)面在application/config/routes.php
拿實(shí)際路由代碼解釋
$route['default_controller']='pages/view';
//這里定義的是默認(rèn)c,訪問(wèn)的是pages頁(yè)面 中view函數(shù)(這里可以這樣理解,也可以說(shuō)為方法)
$route['blog']='blog';//設(shè)置index.php/blog 訪問(wèn)的是blog
$route['pages/(:any)'] = 'pages/view/$1';
//設(shè)置index.php/(:any) 訪問(wèn)的是pages/view/$1 $1表示后面的(:any) 的任意參數(shù)
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
下面的兩個(gè)同上面的
3.進(jìn)行路由后找對(duì)應(yīng)的c層(controllers) c層在application/controllers 下
仍然按照上面的默認(rèn)訪問(wèn)為news 下面列出news在 controllers的代碼,文件名為pages.php
class news extends ci_controller {
public function __construct(){//初始化
parent::__construct();
//必須進(jìn)行父類的初始化
$this->load->model('news_model');
//如果沒(méi)有數(shù)據(jù)交互可以沒(méi)有model的調(diào)用
}
public function index(){
//定義的index函數(shù),如果沒(méi)有controller的函數(shù)部分,則默認(rèn)調(diào)用index漢化
$data['news']=$this->news_model->get_news();
//調(diào)用上面初始化的model進(jìn)行數(shù)據(jù)查詢,并返回給data數(shù)組,這里定義的get_news要看下面的model
$data['title'] = 'news archive';//設(shè)置data數(shù)據(jù)
$this->load->view('templates/header', $data);
//調(diào)用view中的templates/header頁(yè)面 進(jìn)行頁(yè)面展示,并將data數(shù)據(jù)傳遞給view
$this->load->view('news/index', $data);
//這里調(diào)用view中的 news/index 頁(yè)面,并傳遞$data 數(shù)據(jù)
$this->load->view('templates/footer');//不傳遞任何數(shù)據(jù)
}
public function view($slug){
//view函數(shù),如果參數(shù)$slug存在則進(jìn)行查詢,如果不存在則顯示404錯(cuò)誤
$data['news_item'] = $this->news_model->get_news($slug);
//這里定義的get_news要看下面的model
if (empty($data['news_item']))show_404();
//如果獲取的內(nèi)容為空,或者不能獲取,則展示404錯(cuò)誤
$data['title'] = $data['news_item']['title'];
//同樣將數(shù)據(jù)給data,并通過(guò)view進(jìn)行傳值。
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
}
4,下面介紹model層,進(jìn)行的是數(shù)據(jù)調(diào)用和邏輯控制等,在application/models 下,文件名news_model.php
看news_model代碼如下:
class news_model extends ci_model{
public function __construct(){
$this->load->database();//調(diào)用數(shù)據(jù)庫(kù),以后說(shuō)數(shù)據(jù)庫(kù)設(shè)置
}
public function get_news($slug=false){//這里是上面調(diào)用的get_news
if($slug===false){//看是否有查詢參數(shù),如果沒(méi)有獲取全部新聞
$query=$this->db->get('news');
return $query->result_array();
}//如果有,則按照條件進(jìn)行查詢,數(shù)據(jù)調(diào)用以后令講。
$query = $this->db->get_where('news',array('slug'=>$slug));
return $query->row_array();
}
}
5.最后面的是view視圖 在application/views/news/view.php
代碼如下:
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];
echo $news_item['id'];
在頁(yè)面輸入 http://localhost/index.php/news 進(jìn)行訪問(wèn)了
更多信息請(qǐng)查看IT技術(shù)專欄