I'm having some issue understanding this. I'd like to start re-writing some old MySQL function code PDO. The way it was set up, is that an external file containing this line (among other things):
// db.php file
$DB = new dbConnect(SERVER,DB,USER,PASSWORD,3306);
function my_autoloader($class)
{
require_once ($_SERVER['DOCUMENT_ROOT']."/includes/".'class.' . $class . '.php' );
}
spl_autoload_register('my_autoloader');
Which would create a connection to my database. This is included at the very top of my pages and would also load all my classes. Now, if I want to create a new connection using PDO, I would do the following:
$conn = new PDO('mysql:host='.SERVER.';dbname='.DB.';charset=utf8',USER, PASSWORD);
However, I cannot have this line of code on a separate file and call PDO from within a class like the following:
require_once 'db.php';
class info
{
protected $ID;
public function __construct($id)
{
$this->ID = $id; //
}
public function getName()
{
$query = "SELECT * FROM job";
$q = $conn->query($query);
$data = $q->fetch(PDO::FETCH_ASSOC);
//do something with $data
}
}
Does this mean I have to establish a connection in the constructor by means of aggregation like the following?
require_once 'db.php';
class info
{
protected $ID;
protected $pdo;
public function __construct($id)
{
$this->ID = $id; //
$this->pdo = new PDO('mysql:host='.SERVER.';dbname='.DB.';charset=utf8',USER, PASSWORD);
}
public function getName()
{
$query = "SELECT * FROM job";
$q = $this->pdo->query($query);
$data = $q->fetch(PDO::FETCH_ASSOC);
// do something
}
}
Or is there another way of doing this that I'm not aware of. It seems tedious trying to re-write all of my classes to incorporate this.
Instead of creating the database connection inside the constructor, it's better to make it a dependency:
public function __construct(PDO $db, $id)
{
$this->pdo = $db;
$this->ID = $id;
}
To use it, you would do:
// $db = new PDO('mysql:host='.SERVER.';dbname='.DB.';charset=utf8',USER, PASSWORD);
$info = new info($db, '123');
echo $info->getName();
The chief advantage of this approach is that you no longer have any configuration stored inside your class. Additionally, you can pass anything that implements PDO
as well, enabling unit testing with mocked databases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With