I am currently trying to implement a very simple MVC framework as a way of helping me understand how they work. My base controller class has 2 properties, a model and a view. All controllers have a generic view class property however only certain controllers have a model.
I needed a way of obtaining the name of the child controller class in the base controller class so that in the constructor I can check to see if a model class exists and instantiate one if so. I think I have come up with a solution using late static binding. I do not fully understand the concept, but as far as I can tell, if used in a parent class the static keyword refers to the child class.
I also implemented a function className() in the controller class which uses the 'this' keyword to get the name of the current class. This function is then called with the static keyword resulting in the name of the child class being obtained.
Below is the code for the Controller class. All models are titled controllerName_model.
/**
* Base controller class, creates a generic view class and a model class (if one exists for the child class) for the controller.
*/
class Controller
{
public $view;
public $model;
public function __construct()
{
//Create a new genereic view object
$this->view = new View();
//Use late static binding to get the name of the child class extending this base class
$name = static::className();
//Create the path to the related model (if it exists)
$path = 'models/' . $name . '_model.php';
//If the model exists then require the file and create a new model object and store in $this->model
if(file_exists($path)) {
require $path;
$modelName = $name . '_Model';
$this->model = new $modelName();
}
}
/**
* This class returns the name of each class that extends this base controller class. It is used in the
* constructor with late static binding to get the name of the child class so that a model can be created if one exists.
*/
public function className() {
return get_class($this);
}
}
As far as I can tell this method is working but I am not confident that it is correct or that it is the best way of doing this. If anyone knows of any other ways of doing this or can point out any flaws in this approach I would be extremely grateful. Thanks.
get_class($this);
But "that in the constructor I can check to see if a model class exists and instantiate one if so" makes no sense \$\endgroup\$