I'm doing an application in MVC for study purposes, here the structure:
Sketch of my class Model that will be extended by the child classes.
<?php
abstract class Model {
protected $db;
protected $table;
function __construct(PDO $db, $table) {
$this -> db = $db;
$this -> table = $table;
}
public function getAll($where = null) {
$query = "SELECT * FROM {$this->table}";
if ($where)
$query .= "WHERE {$where}";
$query = $this -> db -> prepare($query);
try {
$query -> execute();
return $query -> fetchAll();
} catch(PDOException $e) {
die($e -> getMessage());
}
}
public function getById($id) {
$query = $this -> db -> prepare("SELECT * FROM {$this->table} WHERE id = :id");
$query -> bindParam(':id', $id);
try {
$query -> execute();
return $query -> fetch();
} catch(PDOException $e) {
die($e -> getMessage());
}
}
In the class controller I open the connection:
class Controller {
function __construct() {
}
public function openDB() {
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
$this -> db = new PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET, DB_USER, DB_PASS, $options);
return $this -> db;
}
}
Example of a controller: (Assuming I already inherited the class Controller and includes the class files)
function index() {
$db = $this -> openDB(); /*conexão é aberta*/
$testeModel = new testeModel($db);
$getAll= $testModel-> getAll();
}
When I use the GetById or GetAll function I notice a certain lag, even though the application is in localhost that lag is considerable ... and keep in mind that with These are not the best practice for this, I would like some suggestions that can improve the performance of the application / communication with the bank, but nothing very complex, since I am in a learning process, thank you.