The Controller class is the base class that all controllers in MINI extend. It provides automatic database connection and model loading.Located at: application/core/controller.php
class Controller{ /** * @var null Database Connection */ public $db = null; /** * @var null Model */ public $model = null; /** * Whenever controller is created, open a database connection too and load "the model". */ function __construct() { $this->openDatabaseConnection(); $this->loadModel(); }}
Loads the Model class and passes the database connection to it.
public function loadModel(){ require APP . 'model/model.php'; // create new "model" (and pass the database connection) $this->model = new Model($this->db);}
After this call, $this->model is available in all controller methods.
class Songs extends Controller{ public function customQuery() { // Direct PDO access via $this->db $sql = "SELECT * FROM song WHERE artist LIKE :search"; $query = $this->db->prepare($sql); $query->execute([':search' => '%Beatles%']); $results = $query->fetchAll(); // ... use $results in view }}
Create a new file in application/controller/, e.g., blog.php.
2
Extend Controller Class
blog.php
class Blog extends Controller{ public function index() { // $this->db and $this->model are automatically available $posts = $this->model->getAllPosts(); require APP . 'view/_templates/header.php'; require APP . 'view/blog/index.php'; require APP . 'view/_templates/footer.php'; }}
3
Access via URL
Navigate to example.com/blog to call the index() method.
Use the Model for Database LogicWhile you can access $this->db directly, it’s better to put database queries in the Model class for better organization and reusability.
// Good:$songs = $this->model->getAllSongs();// Less ideal:$query = $this->db->prepare("SELECT * FROM song");$query->execute();$songs = $query->fetchAll();
Don’t Put Business Logic in ViewsControllers should prepare all data before loading views. Views should only display data, not query the database or perform calculations.
public function add(){ if (isset($_POST['submit_add_song'])) { // Process form submission $this->model->addSong( $_POST['artist'], $_POST['track'], $_POST['link'] ); // Redirect after processing header('location: ' . URL . 'songs'); }}