Using PDO with MVC
- by mister martin
I asked this question at stackoverflow and received no response (closed as duplicate with no answer). I'm experimenting with OOP and I have the following basic MVC layout:
class Model {
// do database stuff
}
class View {
public function load($filename, $data = array()) {
if(!empty($data)) {
extract($data);
}
require_once('views/header.php');
require_once("views/$filename");
require_once('views/footer.php');
}
}
class Controller {
public $model;
public $view;
function __construct() {
$this->model = new Model();
$this->view = new View();
// determine what page we're on
$page = isset($_GET['view']) ? $_GET['view'] : 'home';
$this->display($page);
}
public function display($page) {
switch($page) {
case 'home':
$this->view->load('home.php');
break;
}
}
}
These classes are brought together in my setup file:
// start session
session_start();
require_once('Model.php');
require_once('View.php');
require_once('Controller.php');
new Controller();
Now where do I place my database connection code and how do I pass the connection onto the model?
try {
$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_DATABASE.'', DB_USERNAME, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $err) {
die($err->getMessage());
}
I've read about Dependency Injection, factories and miscellaneous other design patterns talking about keeping SQL out of the model, but it's all over my head using abstract examples. Can someone please just show me a straight-forward practical example?