在数组中加载多个模型 - codeigniter框架

Mad*_*ota 3 codeigniter

<?php
class Home extends CI_Controller
{
    public function __construct()
    {
        // load libraries //
        $this->load->library('session');
        $this->load->library('database');
        $this->load->library('captcha');

        // alternative
        $this->load->library(array('session', 'database', 'captcha'));

        // load models //
        $this->load->model('menu_model', 'mmodel');
        $this->load->model('user_model', 'umodel');
        $this->load->model('admin_model', 'amodel');

        // alternative
        $this->load->model(array(?));
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

如何在阵列中加载所有模型?可能吗?

Wes*_*rch 5

对于模型,您可以这样做:

$models = array(
    'menu_model' => 'mmodel',
    'user_model' => 'umodel',
    'admin_model' => 'amodel',
);

foreach ($models as $file => $object_name)
{
    $this->load->model($file, $object_name);
}
Run Code Online (Sandbox Code Playgroud)

但如上所述,您可以创建文件application/core/MY_Loader.php并编写自己的方法来加载模型.我认为这可能有效(未经测试):

class MY_Loader extends CI_Loader {

    function model($model, $name = '', $db_conn = FALSE)
    {
        if (is_array($model))
        {
            foreach ($model as $file => $object_name)
            {
                // Linear array was passed, be backwards compatible.
                // CI already allows loading models as arrays, but does
                // not accept the model name param, just the file name
                if ( ! is_string($file)) 
                {
                    $file = $object_name;
                    $object_name = NULL;
                }
                parent::model($file, $object_name);
            }
            return;
        }

        // Call the default method otherwise
        parent::model($model, $name, $db_conn);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用上面的变量:

$this->load->model($models);
Run Code Online (Sandbox Code Playgroud)

您还可以允许在数组中传递单独的数据库连接,但是您需要具有多维数组,而不是我们使用的简单数组.不管怎样,你不需要经常这样做.