Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO & custom Database wrapper class: static or instance? [closed]

Tags:

oop

php

mysql

pdo

I was looking for a good PDO wrapper class in PHP; as no class among those I have seen suited my needs, I decided to write my own one, enhancing a class I already wrote before that used the now-dreaded mysql_* functions to integrate the native escaping, db-agnosticity, prepared statements and so on.

One thing I was wondering is, what is the best approach in developing and using a class like this? One alternative would be by instances:

$db = new Database();
$db->query("SELECT this FROM that");

The other would be with static methods:

DB::query("SELECT foo FROM bar WHERE answer=42");

I've seen some frameworks (f.ex. Joomla API) that prefer to use the first method, but I am not sure of which could be the possible pitfalls of the second approach.

Have you got any insights?

like image 650
Cranio Avatar asked Dec 05 '25 10:12

Cranio


1 Answers

I personally don't see the need for a PDO wrapper class (PDO is a database wrapper class in on itself).

However, if you wish to do it, do it as an instance, for several reasons:

  1. It makes more sense, you may want more than one database connection.
  2. It's easier to use.
  3. It uses less global space, which is evil.
  4. It makes me happy.

So yeah, instance is the way to go, although I would just use native PDO for most tasks.

like image 76
Madara's Ghost Avatar answered Dec 07 '25 23:12

Madara's Ghost