2013-12-12 113 views
0

今天我決定開始依靠PHP框架,因爲每次從頭開始編寫都非常耗時。作爲我的框架,我選擇了CodeIgniter,並且我想說這很棒,易於使用。但我有一些問題和困惑。我不確定如何構建我的網站,因爲我不知道何時使用模型以及何時使用控制器。
我有現在的問題是:

CodeIgniter模型和控制器混淆

頁面控制器

// PAGES CONTROLLER 
// As its name, this controller simply loads pages by a url query. 
class Pages extends CI_Controller { 
    /* 
    * Constructor - loads the variables model. 
    */ 
    public function __construct() { 
     parent::__construct(); 
     $this->load->model ('variables'); 
    } 
    /* 
    * Displays a page by its name. 
    */ 
    public function view($page = 'home') { 
     if (! file_exists ("application/views/pages/$page.php")) { 
      show_404(); 
     } 
     $data ['title'] = ucfirst ($page); 
     $data ['variables'] = $this->variables; 

     $this->load->view ("templates/header", $data); 
     $this->load->view ("pages/$page", $data); 
     $this->load->view ("templates/footer", $data); 
    } 
} 


變量模型

// VARIABLES MODEL 
// Used like a "mysql variables", all the data is taken from a table contains 2 
// rows: id and value. and those variables are mostly used for site settings. 
class Variables extends CI_Model { 
    /* 
    * Constructor, simply loads the database. 
    */ 
    public function __construct() { 
     $this->load->database(); 
    } 
    /* 
    * Gets a variable stored in the database. 
    */ 
    public function get($id) { 
     $query = $this->db->get_where ('variables', array (
       'id' => $id 
     )); 
     return $query->row_array()["value"]; 
    } 
    /* 
    * Sets a variable stored in the database. 
    */ 
    public function set($id, $value) { 
     $this->db->where ('id', $id); 
     $this->db->update ('variables', array (
       'value' => $value 
     )); 
    } 
} 

我使用正確的層次結構?有什麼我可以改變的嗎?

現在我的主要問題:讓我們說,例如,我想爲我的網站添加一個會員功能。我應該做以下事情嗎? :

成員控制器 - 管理當前成員,並且所有表單操作都導致與成員模型通信的此控制器(請參見下文)。

成員模型 - 處理所有的數據庫處理,功能如:login,register,getMember。

+0

處理請求和傳遞數據查看,同時使用型號爲您所有的數據庫交互和實施系統的所有業務邏輯模型中使用視圖只用於顯示數據 –

+0

@MKhalidJunaid使用控制器非常感謝您的快速回答,我已經知道你剛剛告訴我的是什麼,但是我的主要問題是如果我對我給出的例子正確。 –

+0

你也應該看看HTML5鍋爐板的建設網站結構.... http://ariok.github.io/codeigniter-boilerplate/ – Christopher

回答

2

我只是想在你的控制器建議你可以在兩行做到這一點:

$this->load->view ("templates/header", $data); 
    $this->load->view ("pages/$page", $data); 
    $this->load->view ("templates/footer", $data); 

既然你可以加載一個視圖中你的看法,那麼你可以嘗試:在您看來e.g template.php

$this->load->view('templates/header'); 
    $this->load->view($main_content); 
    $this->load->view('templates/footer'); 

而且你可能希望你的控制器沒有太多的代碼,因爲所有繁重的任務應該在你的模型中,所以在你的控制器:

$data['main_content'] = $page; 
    $this->load->view('templates/template',$data); 
+0

謝謝你的建議!所以你簡單地將頁面名稱分配給main_content變量,但是如何在視圖中顯示它?我需要使用什麼功能? –

+0

'$ data ['main_content']'等於將要加載的頁面。 – leonardeveloper

+0

嘗試檢查這個系列,不會錯過任何一個http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-day-1/ – leonardeveloper