在整个项目中,我需要此模型的功能(实际上我需要$data
)。
当我调用某个控制器$data = $this->multi_language_model->multi_lang();
时,它可以正常工作。但是可以在一个地方调用,所以我可以在每个控制器和视图中使用。
我自动加载模型
$autoload['model'] = array('multi_language_model');
class Multi_language_model extends MY_Model
{
public function __construct() {
parent::__construct();
}
public function multi_lang() {
$data['menu_delivery'] = $this->lang->line('menu_delivery');
$data['menu_quotations'] = $this->lang->line('menu_quotations');
$data['menu_customer_service'] = $this->lang->line('menu_customer_service');
return $data;
}
}
答案 0 :(得分:1)
将此帮助程序功能放入任何已加载的帮助程序中:
function get_multi_lang(){
$CI = & get_instance();
$data = array();
$CI->load->helper('language');
$CI->lang->load('menu','english');
$data['menu_delivery'] = $CI->lang->line('menu_delivery');
$data['menu_quotations'] = $CI->lang->line('menu_quotations');
$data['menu_customer_service'] = $CI->lang->line('menu_customer_service');
return $data;
}
控制器:
class Yourclassname extends CI_Controller {
var $menu_delivery = "";
var $menu_quotations = "";
var $menu_customer_service = "";
function __construct() {
parent::__construct();
$data = get_multi_lang();
$this->menu_delivery = $data['menu_delivery'];
$this->menu_quotations = $data['menu_quotations'];
$this->menu_customer_service = $data['menu_customer_service'];
}
public function index(){
echo $this->menu_delivery.'<pre>';
echo $this->menu_quotations.'<pre>';
echo $this->menu_customer_service.'<pre>';die;
}
}
如果您不想使用辅助函数,则在控制器__construct()中复制辅助函数行[将$ data替换为$ this->],以便直接使用全局变量在模型中也是如此,以便视图通过控制器传递此变量>
答案 1 :(得分:0)
我不知道codeigniter的工作原理,但也许您可以静态地使用此方法,并像这样使用它:
class Multi_language_model extends MY_Model
{
private static $data = [];
public function get_multi_lang()
{
return [
'menu_delivery' => $this->lang->line('menu_delivery'),
'menu_quotations' => $this->lang->line('menu_quotations'),
'menu_customer_service' => $this->lang->line('menu_customer_service'),
];
}
public static function multi_lang()
{
if (empty(self::$data)) {
self::$data = (new self)->get_multi_lang();
}
return self::$data;
}
}
然后,只要需要,就可以使用$data = Multi_language_model::multi_lang()
;
但是,无论您在何处将其从容器中注入,我都看不到任何错误。这样做将更容易构建测试。
顺便说一句,如果没有为扩展类设置自定义参数,则无需覆盖类构造函数。您可以安全地删除:
public function __construct() {
parent::__construct();
}