Database abstraction class design using PHP PDO

牧云@^-^@ 提交于 2019-11-30 15:26:27
Gordon

You don't need the Singleton.

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.

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.

Maybe it seems so simple to you, because PDO is essentially a database abstraction class. That means: the work is already done.

NikiC

Yeah, this is a good start. PDO + singleton is an often-used and great combination. As I personally don't like all the typing involved than using singletons, I have written a very lightweight database class.

It introduces only two additional features over PDO: Access of (lazy) PDO instance using __callStatic (DB::query() instead of DB::instance()->query()) and two functions for easier quoting (DB::q('INSERT INTO table (name) VALUES (?s)', $_POST['insecure_name'])). Maybe you want to look at both, it's really handy ;)

ajporterfield

You may also be interested in the project php-pdo-wrapper-class. It's a light-weight database class that extends PDO, adding several methods - insert, update, delete, select (and a few others) - for simplifying common SQL statements. I've used this project in my development and would highly recommend.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!