使用PHP PDO的数据库抽象类设计 [英] Database abstraction class design using PHP PDO

查看:143
本文介绍了使用PHP PDO的数据库抽象类设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计Web应用程序(实际上,这是一种业余爱好,我正在尝试自学设计,还有什么比做它更好的方法了:).无论如何,我在考虑如何处理数据库.我对 PDO 感到满意,并且我正在考虑在抽象类中利用PDO.我正在考虑建立一个单例,以便只有一个数据库连接.这个单例将创建PDO连接.

I am in the process of designing a web application (really, it's a hobby, and I'm trying to teach myself design, and what better way is there than doing it :). Anyway, I was thinking about how I would deal with my database. I am comfortable with PDO, and I was thinking of leveraging PDO in my abstraction class. I am thinking of making a singleton, so that there's only one database connection. This singleton would create a PDO connection.

在那之后,我看不到为什么我需要做太多其他事情.然后,我可以只使用数据库处理程序来调用PDO函数.我可能需要一些辅助函数,但是当它涉及到它时,我只会在实际的SQL查询中使用PDO.

After that, I fail to see why I would need to do too much else. I can then just use the database handler to call PDO functions. I may want some helper functions, but when it gets down to it, I would just use PDO for the actual SQL queries.

这种方法有什么问题吗?与我使用的抽象类相比,它似乎过于简单.

Is there something wrong with this approach? It seems overly simple compared to the abstraction classes I've used.

推荐答案

您不需要Singleton.

You don't need the Singleton.

数据库Singleton无法解决任何并发问题.如果有的话,可以确保您只有一个PDO实例用于创建它的请求.它提供了全球访问权限,许多人认为这是一件坏事.另外,在测试单例.

A database Singleton won't solve any concurrency issues. If anything, it can make sure you have only one PDO instance for the request it was created in. And it provides global access, which many people consider a bad thing. In addition you have to make some extra effort when testing the Singleton.

只需创建一个包装,在需要时将它们懒惰地连接并存储实例,并在您的引导程序和将实例设置为您的 DAL TableDataGateway .而且,这样一来,您就不会将自己限制为仅一个PDO实例,以防万一某个时候需要另一个PDO实例.

Just create a wrapper that lazy connects and stores the instance when needed in your bootstrap and set the instance to your DAL supertype, for instance a TableDataGateway. Also, this way you don't limit yourself to only one PDO instance in case you will need a second one at some point.

这篇关于使用PHP PDO的数据库抽象类设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆