[英]Codeigniter Model autoloading not working for MY_Loader class
I've added "header_model" into codeigniter's autoload.php file. 我已经将“ header_model”添加到codeigniter的autoload.php文件中。 now its:
现在它:
$autoload['model'] = array("header_model");
And i also can successfully use $this->header_model
in other controllers. 我也可以在其他控制器中成功使用
$this->header_model
。
But can't use it in MY_Loader
class, which is extension of CI_Loader
. 但不能使用它
MY_Loader
类,这是扩展CI_Loader
。
Example: Pages controller located at application/controllers/ : 示例: 位于应用程序/控制器/处的页面控制器:
class Pages extends CI_Controller {
public function view($page = 'home')
{
var_dump($this->header_model->get_menus()); //echoes data from database.
}
}
MY_Loader class (located at application/core/ folder) : MY_Loader类(位于应用程序/核心/文件夹中) :
<?php
class MY_Loader extends CI_Loader {
function __construct()
{
parent::__construct();
}
public function template($template_name, $vars = array(), $return = FALSE)
{
$menuArray = $this->header_model->get_menus(); //echoes errors
//like: Undefined property: MY_Loader::$header_model
$vars["menuArray"] = $menuArray;
}
}
Thanks for any help. 谢谢你的帮助。
The problem is that $this
is two different objects in Pages
and MY_Loader
. 问题在于
$this
是Pages
和MY_Loader
两个不同的对象。
Autoloaded classes, including models, wind up being variables in the controller. 自动加载的类(包括模型)最终成为控制器中的变量。 So
$this->->header_model...
works within Pages
because it is a controller. 所以
$this->->header_model...
在Pages
因为它是一个控制器。 But the object $this
inside the function template
is the instance of the MY_Loader
class. 但是函数
template
中的$this
对象是MY_Loader
类的实例。 And that class has no variable called header_model
. 而且该类没有名为
header_model
变量。
In order to reference the controller use get_instance()
. 为了引用控制器,请使用
get_instance()
。 Here's how 这是如何做
public function template($template_name, $vars = array(), $return = FALSE)
{
$CI =& get_instance();
$menuArray = $CI->header_model->get_menus(); //echoes errors
//like: Undefined property: MY_Loader::$header_model
$vars["menuArray"] = $menuArray;
}
Not part of your problem but I'd like to point out that you do not need the __construct()
function in MY_Model
. 这不是问题的一部分,但我想指出的是,您不需要
MY_Model
的__construct()
函数。 If a child class does not do any initialization in a constructor there is no need to create a constructor only to call parent::__construct();
如果子类未在构造函数中进行任何初始化,则无需创建构造函数仅需调用
parent::__construct();
. 。 PHP will find the parent class constructor execute it automatically.
PHP将发现父类构造函数自动执行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.