开发者

Why should I make database wrapper?

开发者 https://www.devze.com 2023-02-10 02:38 出处:网络
I\'m actually wondering why 开发者_高级运维should I need database wrapper for PHP. Like wrapper for MySQLi or PDO. It\'s class that calls PDO/MySQLi class. Why should I need it? Advantages? I will try

I'm actually wondering why 开发者_高级运维should I need database wrapper for PHP. Like wrapper for MySQLi or PDO. It's class that calls PDO/MySQLi class. Why should I need it? Advantages? I will try to make one - just I don't get the main goal. Why do I need it?? =]


I can think of at least two reasons:

1) Refactoring. Technology changes, so you should strive to localize the needed changes (in order to do them fast and without risk). A few years back you did not have MySQLi or PDO. If you would have developed a wrapper for the classical MySQL extension, you could have easily switched to, say, PDO, without having to change all of the wrapper clients. Replacing hundreds of calls from mysql_connect() to mysqli_connect() on the other hand, doesn't sound so appealing.

2) Testability. If you practice automated testing, adding a layer of indirection (the wrapper), means you could easily substitute it with a fake one. As a consequence, you control if the queries really go to the database or, for instance, get logged to a file. The result is faster and more manageable tests.


Abstractions like PDO intend to make things more secure. You could say that the database execution you want to do will be "strongly typed" which means that something like this will be prevented:

$myDangerousSql = "select * from dbA where x ='"+$someVariable+"'";

The above could result in something called sql-injection.

When using PDO you explicitly say "x will be of type string" or whatever type you use in your database. In this way the statement can be "prepared" and thus you cannot "inject" new SQL-code into it. Which makes it more secure.

This is just one of the reasons though, but most likely the biggest one. And don't write your own wrapper/abstraction if it's not for learning purpose, there are a lot of good ones out there already.

Here is a good post talking about Database abstraction in PHP.


I am not clear what you are asking here. But I would assume PDO is already what you are talking about, it is "data-access abstraction layer" which means you can use the same code to talk with a variety of DBMS' and easily switch between them without having to change your code (providing you use SQL which is compatible with what you are switching between).

MySQLi is the extension used to access MySQL databases directly, and there are also extensions for Oracle and other DBMS'.


If you are going to use a wrapper on top of PDO, don't write one, there are lots already written. You've Doctrine, ActiveRecord, Zend_Db, and probably many more.

  • http://www.phpactiverecord.org/
  • http://www.doctrine-project.org/
  • http://framework.zend.com/manual/en/zend.db.html
0

精彩评论

暂无评论...
验证码 换一张
取 消