Re-Usable Objects and Configuration
Sat, 10 Sep 2011When you are building a framework or series of objects it's best practice to have a dedicated folder for system-wide configuration. This may sound like a no brainer, but let me take it a bit further with your objects.
The Incorrect Way
Lets say you have a configuration file, and a class for connecting to a database and it looks something like this:
./config/database.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_TYPE', 'mysql');
./libs/Database.php
<?php
class Database extends PDO {
public function __construct()
{
try {
parent::__construct(DB_TYPE . ':dbname='DB_NAME .';host=' . DB_HOST, DB_USER, DB_PASS);
catch (PDOException $e) {
die($e->getMessage());
}
}
}
So far so good, right? No. If you examine the class above it is relying on the configuration file. Isn't that what we want? Nope! We want our classes to be separate from the configuration file, because we may decide to use the object without a configuration file. At the moment, the Database object is now dependent on the configuration file, we do not want this!
The Correct Way
The solution is passing your pre-defined configuration settings during instantiation, see below:
<?php
class Database extends PDO {
public function __construct($db_type, $db_name, $db_host, $db_user, $db_pass)
{
try {
parent::__construct("$db_type:dbname=$db_name;host=$dbhost", $db_user, $db_pass);
catch (PDOException $e) {
die($e->getMessage());
}
}
}
Doing it this way allows you to re-use your object in more scenarios, we are now decoupled from the configuration file:
<?php $db = new Database(DB_TYPE, DB_NAME, DB_HOST, DB_USER, DB_PASS);
I hope this has helped you see a little bit behind the train of thought it takes to build a flexible and re-usable system with one of these basic steps. Lastly, for the sake of pretty-ness you could clean up the construct by passing in an array, but it's up to you;