load multiple models in array - codeigniter framew

2019-02-18 22:55发布

问题:

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

How can i load all models in array? is it possible?

回答1:

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.



回答2:

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


回答3:

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



回答4:

This work fine for me:

$this->load->model(array('menu_model'=>'menu','user_model'=>'user','admin_model'=>'admin'));


标签: codeigniter