So, my question is more of a 'best practices' question rather than a question with a particular aim. This is my current understanding of PHP factories and how to incorporate them into a project using PDOs and dependency injection. I'm pretty new at this and I still don't understand a lot about this subject. As such, I really don't know if I'm doing this quite right. Could someone point me in the right direction?
<?php
class PDOSettings_Factory {
private function __construct() {}
public static function build(Array $args = NULL) {
$settings = array();
// Set default values.
$settings["dbType"] = 'mysql';
$settings["dbName"] = 'test';
$settings["host"] = 'localhost';
$settings["user"] = 'guest';
$settings["pass"] = '1234';
// If keys are the same, they will be overwritten.
if(isset($args)) {
foreach($args as $key => $val) {
$settings[$key] = $val;
}
}
// Return setings.
return $settings;
}
}
$settings = PDOSettings_Factory::build();
class PDOConnection_Factory {
private function __construct() {}
public static function build($args) {
// Set up PDO connection
if(!isset($args)) {
return NULL;
} else {
$statement =
$args['dbType'].':'.
'host='.$args['host'].';'.
'dbname='.$args['dbName'];
try {
$dbh = new PDO(
$statement,
$args['user'],
$args['pass']);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Return DBH
return $dbh;
} catch (PDOException $e) {
echo 'Error: ', $e->getMessage(), "\n";
}
}
return NULL;
}
}
And how to use the factories:
class demo {
private $dbh = NULL;
public function set($args) {
if (!isset($args)) {return FALSE;}
else {
$this->dbh = $args;
return TRUE;
}
}
public function __construct($args = NULL) {
$this->set($args);
}
public function doSomething() {
// Set SQL command here.
$sql = 'SELECT * FROM test';
$results = $this->dbh->prepare($sql);
// Perform param binds here.
$results->execute();
return $results;
}
}
$db = PDOConnection_Factory::build($settings);
$test = new demo($db);
foreach ($test->doSomething() as $row) {print_r($row[0].PHP_EOL);}
?>