dpylt7626401 2016-02-01 11:23
浏览 44
已采纳

另一个模型中的PHP MVC调用模型

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.

  • 写回答

1条回答 默认 最新

  • dongshi3061 2016-02-01 11:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改