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.

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

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line