模型验证方法——MVC(CodeIgniter)
我有一个模型,其中有一个包含 22 个字段的主表和 5 个连接表——一些输入数据可能需要在数据库中检查,并在插入之前从值转换为 id。
目前我有 950 行代码块,可以一次性完成验证/数据库检查/转换。我看到的问题是代码不太灵活并且难以测试。我还必须为每个其他插入/更新操作复制粘贴/重写它,具体取决于它是否使用类似的字段。
有没有一种对您有用的方法可以推荐给我?将每个字段分成自己的函数? (那么我还必须通过验证和转换来分隔每个字段?)
I have a model which has one main table with 22 fields and 5 join tables -- some input data may need to be checked in the DB and converted from a value to id before insertion.
Currently I have a 950 line chunk of codes that does validation/db checks/conversions all in one go. The problem I see is that the code isn't very flexible and hard to test. I'd also have to copy-paste/rewrite it for every other insert/update action depending if its using similar fields or not.
Is there an approach that has worked for you that you could suggest me? Separate each field into its own function? (Then I'd have to also separate each field, and by validation and conversion?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您将其分解为更多方法......每个方法应该做一件事,并且只做一件事。这使得测试变得容易并且更加灵活。如果您的方法超过 10-20 行,那么它们可能做得太多了。
一旦您的类中获得了每个方法执行一件事的方法集合,那么您就可以创建您实际调用的方法,并让它为您调用那些较小的方法。
这样做可以让您的控制器仍然进行相同的单一方法调用,但您的验证代码现在更具可重用性和可测试性。
I suggest you break that down into more methods... each method should do one thing, and one thing only. That makes it easy to test, and more flexible. If your methods are more than 10-20 lines, they may be doing too much.
Once you've got a collection of methods in your class that each do one thing, then you can create the method you'll actually call, and have it call those smaller methods for you.
Doing this lets your controller still make the same one method call, but your validation code is now more reusable and testable.