PDO课程的最佳做法? [英] Best practices for a PDO class?
问题描述
我想创建一个PDO类来处理数据库连接.
I want to create a PDO class for handling data base connections.
这就是我所拥有的:
require('php/packages/store/store_db_settings.php');
class store_pdo
{
private $DBH; // Data Base Handler
function __construct()
{
$DBH = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
}
public function getHandler()
{
return $DBH;
}
}
我认为这似乎还可以,但是我已经习惯于仅使用mysql_query
之类的东西,并且不太确定将来会遇到什么问题.所以我认为这里的经验可以提供指导.
I think this seems ok, however I am used to just using things like mysql_query
and not really sure what problems I could run into in the future. So I thought the experience here could offer guidance.
我有足够的吗?应该让我的类成为Singleton还是使用静态函数?有最佳实践吗?
Is what I have sufficient? should I make my class Singleton, or use static functions? Is there a best practice?
我不想这样做,然后在使用了其他几个类之后,发现我应该以不同的方式编写它.
I don't want to go with this, then I after have several other classes using it, discover that I should have written it differently.
P.S.我只是注意到best-practices
标记不再允许...这是否也就不鼓励像这样的问题?
P.S. I just noticed that the best-practices
tag is no longer allowed... does that mean questions like this are discouraged now too?
推荐答案
单例和静态类都可以正常工作.我想不出什么情况会有所作为.
A Singleton and a static class would both work fine. I can't think of a situation when it would make a difference.
请确保如果有可能使用多个连接,则可以从一开始就使Singleton/Static类具有多连接功能(使用连接数组或对象属性...)
Make sure that if there ever may be the possibility of using multiple connections, you make your Singleton/Static class multi-connection capable from the start (using an array of connections, or object properties...)
可以说,所有这些方法都创建了某种上帝对象",除了美化了global
之外,什么都没有,并且违反了真正的面向对象编程的原则.我问了有关此问题的问题一旦获得了很多好评.
It could be argued, though, that all these methods create a "God Object" of some sort, are nothing but a glorified global
, and go against the principles of real OOP. I asked a question about this once that yielded a lot of great feedback.
这篇关于PDO课程的最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!