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