在数组中加载多个模型-Codeigniter框架 [英] load multiple models in array - codeigniter framework
本文介绍了在数组中加载多个模型-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(?));
}
}
?>
如何加载数组中的所有模型?
How can i load all models in array? is it possible?
推荐答案
对于模型,您可以执行以下操作:
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);
}
但是如上所述,您可以创建文件 application / core / MY_Loader.php
并编写您自己的模型加载方法。我认为这可能有效(未经测试):
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.
这篇关于在数组中加载多个模型-Codeigniter框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文