load multiple models in array - codeigniter framework

后端 未结 4 1910
暖寄归人
暖寄归人 2021-01-14 05:37
load->library(\'session\');
            


        
相关标签:
4条回答
  • 2021-01-14 06:26

    Not natively, but you can easily extend Loader->model() to support that logic.

    0 讨论(0)
  • 2021-01-14 06:33

    For models, you can do this:

    $models = array(
        'menu_model' => 'mmodel',
        'user_model' => 'umodel',
        'admin_model' => 'amodel',
    );
    
    foreach ($models as $file => $object_name)
    {
        $this->load->model($file, $object_name);
    }
    

    But as mentioned, you can create file application/core/MY_Loader.php and write your own method for loading models. I think this might work (not tested):

    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);
        }
    }
    

    Usage with our variable from above:

    $this->load->model($models);
    

    You could also allow a separate DB connection to be passed in an array, but then you'd need to have a multidimensional array, and not the simple one we used. It's not too often you'll need to do that anyways.

    0 讨论(0)
  • 2021-01-14 06:35

    I don't have any idea about the CodeIgniter 2.x but in CodeIgniter 3.x, this will also works :

    $models = array(
       'menu_model' => 'mmodel',
       'user_model' => 'umodel',
       'admin_model' => 'amodel',
    );
    $this->load->model($models);
    
    0 讨论(0)
  • 2021-01-14 06:38

    This work fine for me:

    $this->load->model(array('menu_model'=>'menu','user_model'=>'user','admin_model'=>'admin'));
    
    0 讨论(0)
提交回复
热议问题