从函数内部进行 SQL 调用
我有一个在多个地方使用的 PHP 函数(称为 funcA),因此我将 funcA(和一些相关函数)放在一个单独的文件中,该文件在其他 PHP 文件中 require
。 funcA 对已打开并由调用它的代码使用的数据库进行大量查询。这些查询是通过 MDB2 对象完成的。
现在,在调用 funcA 的地方,调用例程将一个已连接的 MDB2 对象指针传递给它。这很好用。
我想知道是否最好通过不传递 MDB2object 指针并使用 funcA require
MDB2 并使用其自己的 mdb2 对象连接到数据库来使 funcA 完全独立。它需要更多的内存、更多的 CPU 周期和更多的网络流量,但这是更好的做法吗?
I've got a PHP function (call it funcA) that is used in multiple places, so I placed funcA (and some related functions) in a separate file that is require
d in other PHP files. funcA makes numerous queries on a database that is already open and used by the code that calls it. Those queries are done via an MDB2 object.
As it stands now, where funcA is called, the calling routine passes an already-connected MDB2 object pointer to it. This works fine.
What I'm wondering is if it would be better to make funcA completely self-contained by not passing the MDB2object pointer and instead having funcA require
MDB2 and connect to the database with its own mdb2 object. It's more memory, more CPU cycles, and more network traffic, but is it a better practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“最佳实践”是几乎无法定义的事情之一。然而,在我看来,如果一个函数依赖于其他东西,最好将该依赖项传递到该函数中 - 正如您现在所做的那样。
这允许您的函数执行它所做的任何事情,而不必担心查找和连接到数据库。它还允许您使用虚拟数据库测试您的函数。
它通常称为依赖注入,并在面向对象的体系结构中广泛推荐。
"best practice" is one of those things that are almost impossible to define. However, in my view, where a function depends on something else, it's best to pass that dependency into the function - as you're doing now.
This allows your function to do whatever it does, without having to worry about finding and connecting to the database. It also allows you to test your function with a dummy database.
It's generally known as dependency injection, and widely recommended in object oriented architectures.
有些人可能也认为这是不好的做法,但这种情况下的解决方案可能是 注册表模式或单例 PDO 类。
我不想就单例或注册表的正确与错误展开全面讨论,但在这种情况下,它可能是最干净的解决方案,不涉及重构应用程序的很大一部分。
一些非常基本的示例(您应该仔细阅读上面的链接,因为了解这些模式可以为您节省大量时间和麻烦)
Some might call it bad practice too but a solution in this situation might be the Registry pattern or a Singleton PDO class.
I don't want to start a whole discussion on the right and wrong of singletons or registries but in this case it might be the cleanest solution that doesn't involve refactoring a large part of your application.
Some really basic examples (you should really read up on the links above since understanding these patterns can save you alot of time and trouble)