Sorry if the question has already been asked, but I have wanted to know if import a model in another model MVC is correct or whether it is best to do the same function in EVERY models?
For now in the Model in my Library folder I add the same method as in my Controller:
class Model
{
protected function __construct()
{
$this->db = new Database;
}
public function model($model)
{
require_once '../app/models/' . $model . '.php';
return new $model();
}
}
And in my model file :
class Exemple_model extends Model
{
function __construct ()
{
parent::__construct();
}
public function exemple_function()
{
$otherModel = $this->model('urlAnotherModelFile');
$otherModel->otherMethod();
}
}
But I am not sure it is correct to do so or if is the best way.
Thank you in advance for your answers.
You are kind of mixing things up I think.
Your controller is responsible for creating models, and executing methods on them. You can rename you Model
class to BaseModel
, and make each model extend from this BaseModel
.
As for the problem of including the right files, I would recommend you take a look at the autoloader: http://php.net/manual/de/function.spl-autoload-register.php. This may look a bit confusing at first, but if look at the first example you will quickly understand what is the gist of it: basically if you want to create a object of a specific class, php checks if it already knows that class, and if not, it will execute the autoloader (which then tries to include the file containing the class). As soon as you have configured the autoloader, you can stop caring about including the right files.
As autoloader might be a bit confusing at first, this would be the autoloader in your specific use case:
spl_autoload_register(function ($model) {
include '../app/models/' . $model. '.php';
});
You need to put this snippet somewhere before you construct / access a model. Everything else is done by php (it calls automatically the function as it needs to, so calling something like spl_autoload_register('Comments_model::comments_list');
would not work at all :)
Now if you want to execute a method from a model, you can do this as following:
$otherModel = new otherModel();
$otherModel->otherMethod();
no worries about require
or similar, php does this for you.