The controller is the entry point to our application + the logic of what needs to be done in general. The controller works with Models and passes the result to the View.
Let’s create the main class of the controller from which all other controllers will be inherited in the future. To do this, go to the vendor/core directory and create our new file called Controller.php
Add to this file:
namespace core; abstract class Controller { //data which the controller will receive from model and further will transfer in a View public array $data = []; //page metadata public array $meta = []; //page template public false|string $layout = ''; //page view public string $view = ''; //model object public object $model; //accept the url parameter which is transferred from the Router class public function __construct(public $route = []){ } //get our model public function getModel() { // get our model $model = 'app\models\\' . $this->route['admin_prefix'] . $this->route['controller']; //if the model file exists, create a new instance of this class if (class_exists($model)) { $this->model = new $model(); } } public function getView() { //if there is $this->view then we will write it, if it does not exist we will write $this->route['action'] $this->view = $this->view ?: $this->route['action']; } // a method that will record data for our controller which then pass them in the View public function set($data) { $this->data = $data; } //method that will write our metadata public function setMeta($title = '', $description = '', $keywords = '') { $this->meta = [ 'title' => $title, 'description' => $description, 'keywords' => $keywords, ]; } ?>
All other controllers can now be inherited from our base controller.