I'm developing a small framework for learning purposes, and one of the ways I found to pass the PDO object to be used in controllers / models was to use the following approach:
The constructor method of the parent Controller receives a PDO object, and this is inherited by all "Child Controllers", who also inherit the "loadModel" method, which returns an object already with the PDO that was passed as argument in the parent Controller.
.
DOUBT : Is this a good approach? otherwise, why? what are the advantages and disadvantages? and what would be a good alternative?
COMPLEMENT: I did some research and it looks like the appropriate pattern for this would be Factory, but I do not know what its implementation would look like in my code so it's available to all controllers, even those do not use a connection to the database.
If possible, sample code based on my code
connection.php
<?php
$options = array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_FOUND_ROWS => true
);
$connection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='. DB_CHARSET, DB_USER, DB_PASS, $options);
return $connection;
index.php
// has some validations and handling of route URLs (controller - action) and sets the controller in the $ controller variable, and it receives, through the constructor, the PDO object to be used within the method.
$obj = new $controller($connection);
controller.php (parent controller)
class Controller {
private $connection;
function __construct ($connection) {
$this->connection = $connection;
}
public function loadModel ($model) {
return new $model($this->connection);
}
UserController.php (example controller)
class UserController extends Controller {
function registration () {
$useCRUD = $this->loadModel('userCRUD');
$info = array('name' => 'Joao', 'age' => 25);
$userCRUD->create($info);
}
}
userCRUD.php It receives by the constructor the PDO object and does the CRUD interactions with the database.