0

下面是使用 CodeIgniter 的代码:

我遇到的问题:

  1. 控制器会有一些函数调用view,虽然是分开的,但是和逻辑本身还是很接近的,如果控制器改成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
}

}
4

1 回答 1

1

1.控制器会有一些函数调用view,虽然是分开的,但是和本身的逻辑还是很接近的,如果控制器改成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.我认为很难跟踪代码。

当然。太多的功能没有真正的名字。保持简单。这并不容易,但要给命名和简化整体逻辑一些爱。

于 2011-08-28T17:52:50.793 回答