2011-08-28 45 views
0

這裏的一個更好的設計是用笨代碼:請建議該控制器類

我遇到的問題:

  1. 控制器將有一定的函數調用視圖,它 分離,但是它與邏輯本身還是很接近的,如果控制器更改爲返回JSON或者XML來顯示結果,那麼看起來 很麻煩。

  2. 似乎很多方法,但每一個都取決於另一個。

  3. 我認爲很難跟蹤代碼。

請給一些建議謝謝。 *請注意,它只是控制器類。負載視圖實際上是爲視圖準備數據,不會呈現頁面。另外doXXX函數調用模型只使用模型方法,它不會有任何SQL語句。 MVC是分開的,但控制器也有與視圖或模型相關的功能,使其相當混亂。

class User extends CI_Controller 
{ 

public function register() 
{ 
//check is logged in or not 
//if not logged in , show the register page 

} 

public function show_register_page() 
{ 
//generate the UI needed data , and call the view to render, and will the user will post back a valid_register function 
} 

public function valid_register() 
{ 
//do all the valid logic, if success, 
//do the do_register 
//if fail, valid_register_fail 
} 

public function valid_register_fail() 
{ 
//check is logged in or not 
//show the valid register fail page 
} 

public function show_valid_register_fail_page() 
{ 
//generate the UI needed data , and call the view to render 
} 

public function do_register() 
{ 
//insert data in the db, the Model will be called 
//if something go wrong in db, show the error page 
//if everything is success, show the register success 
} 

public function show_db_error_page() 
{ 
//generate the UI needed data , and call the view to render 
} 

public function show_register_success() 
{ 
//generate the UI needed data , and call the view to render 
} 

} 

回答

1

1.控制器會有一些函數調用圖,它 分離,但它仍然是十分接近與邏輯本身,如果 控制器改變在JSON或XML返回到顯示結果,看來 很麻煩。

取決於您如何組織代碼以及實際傳遞給視圖(模板)的內容。如果結構良好,則可以有一個HTML視圖,一個用於XML,一個用於json,因爲json通常只對視圖變量進行編碼(請參閱json_encodeDocs)。

2.似乎很多方法,但每一個都取決於另一個。

嗯,只是不這樣做:)名稱看起來像你想「編碼」。保持分開。使這些功能其實是行動用戶執行:

register - that action handles the registration process 

請登錄控制器出來的,處理任何你需要:

login - the login action 
lost_password - the lost password action 
register - the registration action 
activate - the registration activation action 

其他一切不屬於那裏。無需顯示某個頁面的操作 - 控制器本身可以決定選擇哪個視圖。

除此之外,您不需要顯示數據庫錯誤。 CI照顧這一點。只需放在需要的地方,並保持簡單。這應該可以幫助您減少方法和代碼的數量。

3.我認爲很難跟蹤代碼。

當然。太多的功能,而不是真正的名稱。保持簡單。這並不容易,但要給予命名並減少一些愛的總體邏輯。

+0

爲什麼我用這麼多的函數分離的結果是因爲我想讓源代碼容易維護,如果人們發現在有效的時候有錯誤,他們可以跳轉到有效函數並修復它。但是,似乎我將代碼分成許多部分,對其他人來說看起來更加複雜。 – DNB5brims

+0

在控制器旁邊,您可以爲動作背後的實際邏輯創建類。這些被稱爲模型。 CI在模型中很弱,因此您需要創建自己的模型結構。在這些模型中,您可以封裝所有內容,並將其分解爲小功能,而不會在控制器操作中分心。 「瘦控制器,胖模式」在開發者之間有一種說法。 – hakre