我应该在图书馆中使用我的模型吗?
我在 codeigniter 中有我的身份验证库,它访问数据库以检查电子邮件/密码组合是否正确。
如果我坚持 MVC 实践,我是否应该将与数据库交互的函数移至我的模型中,或者最好的做法是将其保留在原处以便我将来可以使用它?
对我来说没有太大区别,除了我必须重新编写库并在模型中创建函数之外,但如果这是应该的方式,那就这样吧。
I've got my auth library in codeigniter which accesses the database to check to see if the email/password combination is correct.
If I'm sticking to the MVC practice, should I move the function that interacts with the database to my model, or is it best practice to leave it where it is so I can use it in the future?
Doesn't make much difference to me, other than the fact I'd have to re-write the library and create the function in my model, but if that's the way it should be then so be it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,经验法则是将涉及处理数据和执行数据库查询的所有函数都放入模型中。不同的开发人员有不同的方法,但我认为你不应该破坏 MVC 模型并将数据库代码放入控制器中。
我自己一直在开发一个名为 WolfAuth 的身份验证库,供任何人分叉和贡献/使用: https://github.com/Vheissu/WolfAuth-for-Codeigniter-2.0-
正如您在我的模型中看到的,我有一个获取用户函数,它可以接受针和干草堆值。因此,我可以在我的库中编写一大堆不同的函数,用于通过 ID 获取用户或通过使用不同的参数调用此模型函数而不是调用不同的函数来登录用户。
在 WolfAuth 中,您可以看到所有函数都会使用不同的值调用模型函数 get_users。我相信,当一个函数可以完成这 6 个函数可以做的所有事情时,拥有一个可以检索多个数据的函数而不是编写单独的函数比拥有 6 个函数要干净得多。
因此,回答您的问题:在模型中编写与数据库交互的函数,但在库中保留相同的函数来调用模型函数并返回其值。
另外,如果您想随意获取代码片段并从我的身份验证库中借用想法,并在您的代码库中使用它们(如果它可以帮助您更好地理解分解代码)。
Well generally the rule of thumb is to have all functions that are involved with processing data and performing database queries go in the model. Different developers have different methods, but I think you shouldn't break the MVC model and put database code in your controllers.
I've been developing an auth library myself called WolfAuth for anyone to fork and contribute too / use: https://github.com/Vheissu/WolfAuth-for-Codeigniter-2.0-
As you can see in my model I have a get user function which can accept a needle and haystack value. So I can write a whole bunch of different functions in my library for getting a user by ID or logging a user in by calling this model function with different parameters instead of calling different functions.
In WolfAuth you can see that all functions will call the model function get_users with different values. I believe having one function that can retrieve multiple pieces of data instead of writing separate functions is much cleaner than having 6 functions when one function can do everything those 6 functions can do.
So to answer your question: write the function that interacts with the database in your model, but keep the same function in your library to call the model function and return its value.
Also, if you want feel free to take pieces of code and borrow ideas from my auth library and use them in yours if it helps you understand breaking code up better.