如何避免CodeIgniter中控制器代码臃肿?
控制器采用 MVC 模式来处理用户输入和输出。因此,输入验证和响应准备应该在控制器中完成。
例如,我有一个控制器方法“save”,它:
- 查找输入数据,
- 对数据运行验证器
- 如果输入有效,则 ,加载适当的模型,将其字段设置为输入值,然后调用其 save()< /code> 方法,
- 如果输入无效,则准备数据以重新加载编辑表单,显示表单
所有这些序列都会创建相当混乱的线性代码。我想以某种方式将其分开。我是否要将验证部分移至模型中?听起来不对?我是否创建一个特殊的“库”类来处理输入?
在 Asp.Net MVC 中,这会更好,因为它们已经实现了“对象绑定器”模式。因此,验证和模型字段绑定消失了,控制器变得更轻。 CodeIgniter 有类似的东西吗?
Controllers are there in MVC pattern to process user input and output. So, input validation and response preparation should be done in a controller.
For instance, I have a controller method "save" which:
- looks for input data
- runs a validator on the data
- if inputs are valid, loads an appropriate model, sets its fields to input values, and calls its
save()
method - if inputs are invalid, prepares data to re-load the edit form, shows the form
All this sequence creates quite a mess of linear code. I'd like to separate it somehow. Do I move the validation part to a model? Sounds wrong? Do I create a special "library" class to handle inputs?
In Asp.Net MVC this would be better as they have implemented the "object binder" pattern. Hence, the validation and model field binding goes away and controller gets much lighter. Is there something similar for CodeIgniter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
控制器进行验证并没有被广泛接受,我在模型中按照“保持模型胖,控制器瘦,视图愚蠢”的原则进行验证。
这取决于业务逻辑什么是有效的电话号码等等,所以对我来说将其放在模型中才有意义。
It is not widely accepted that controllers do validation, I do them in model as per "keep your models fat, controllers thin and views dumb".
It depends on the business logic what is a valid phone number and so on, so it only makes sense for me to have it in model.
我会完全按照您所回避的那样做,并将尽可能多的逻辑放入您的模型中。在我看来,控制器确实应该用于启动服务和为视图准备数据。
你应该尽可能多地使用可重用的代码,即验证器、过滤器等。
I would do exactly as you have eluded to and put as much logic into your models as possible. Controllers really should, imo, be used for initiating services and preparing data for views.
You should as much code reusable, ie validators, filters etc..