這裏的一個更好的設計是用笨代碼:請建議該控制器類
我遇到的問題:
控制器將有一定的函數調用視圖,它 分離,但是它與邏輯本身還是很接近的,如果控制器更改爲返回JSON或者XML來顯示結果,那麼看起來 很麻煩。
似乎很多方法,但每一個都取決於另一個。
我認爲很難跟蹤代碼。
請給一些建議謝謝。 *請注意,它只是控制器類。負載視圖實際上是爲視圖準備數據,不會呈現頁面。另外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
}
}
爲什麼我用這麼多的函數分離的結果是因爲我想讓源代碼容易維護,如果人們發現在有效的時候有錯誤,他們可以跳轉到有效函數並修復它。但是,似乎我將代碼分成許多部分,對其他人來說看起來更加複雜。 – DNB5brims
在控制器旁邊,您可以爲動作背後的實際邏輯創建類。這些被稱爲模型。 CI在模型中很弱,因此您需要創建自己的模型結構。在這些模型中,您可以封裝所有內容,並將其分解爲小功能,而不會在控制器操作中分心。 「瘦控制器,胖模式」在開發者之間有一種說法。 – hakre