This code binds your Db object to the global constants. Its going to be difficult to connect to more than 1 database. Your DB class isn't doing anything for you.
The solution to this is: injection. You should pass in the settings for the Db in the constructor. Below is the PDO class from my framework which I think is serving a similar role to what you are trying to achieve with your Db class. The injection is achieved by accepting parameters in the constructor ($setup).
/// PDO wrapper class to ensure DB implements the Evoke Core DB interface.
class PDO extends \PDO implements \Evoke\Core\Iface\DB
public function __construct(Array $setup)
$setup += array(
'DSN' => NULL,
'Options' => array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION),
'Password' => NULL,
'Username' => NULL);
throw new \InvalidArgumentException(__METHOD__ . ' requires DSN');
throw new \InvalidArgumentException(__METHOD__ . ' requires Password');
throw new \InvalidArgumentException(__METHOD__ . ' requires Username');
There are a number of differences with this approach:
- The Db class is a Db type object (extends PDO).
- Common database type functions are ensured (implements Iface\DB).
- Setup for the database is injected (with the setup parameter). This means that many databases could be connected to each with a different set of parameters injected.
- Validity of the setup is enforced.
By creating an interface we can pass any type of object that implements the interface for use as our Db object. This means our code is decoupled from the specific type of database object (I could replace PDO with mysqli very easily if I wanted to).
if (!$db instanceof \Iface\DB)
throw new \InvalidArgumentException(__METHOD__ . ' we need a Db object.');
Personally I have the small PDO wrapper you saw above and then a further abstraction for SQL statements. With everything all of the dependencies are injected (normally in the constructor). You can see more of my Db objects here. Notice how the SQL class is injected with a Db (any sort of DB that implements the DB interface):
class SQL implements \Evoke\Core\Iface\DB
protected $inTransaction = false;
/// Class constructor
public function __construct($setup=array())
$this->setup = array_merge(array('DB' => NULL), $setup);
if (!$this->setup['DB'] instanceof \Evoke\Core\Iface\DB)
throw new \InvalidArgumentException(__METHOD__ . ' needs DB');