假设我有一个像这样叫家的控制器
class Home extends CI_Controller{
public function __construct()
{
parent::__construct();
//load the settings model
$this->load->Model('settings_model');
//get the all settings and store it into a variable
$siteSettings = $this->settings_model->SiteSettings();
//how to pass the data to view
$data['site'] = $siteSettings;
}
public function index()
{
//some code and pass the value to view
$data["some_item"] = "some value";
//Load the view
$this->load->view("home",$data);
}
public function SomeMethod1()
{
//some code and pass the value to view
$data["some_item"] = "some value";
//Load the view
$this->load->view("home",$data);
}
public function SomeMethod2()
{
//some code and pass the value to view
$data["some_item"] = "some value";
//Load the view
$this->load->view("home",$data);
}
}
但我的问题是我想将 $ siteSettings 传递给我的每个方法。我不想每次从 settings_model 获取数据以获取我的不同家庭控制器方法。我只想从 __ construct()获取数据库中的数据,并在调用不同的方法时将值传递给每个方法。
我怎样才能做到这一点?我应该使用公共变量并将获取的数据存储到此变量并从不同的方法调用变量吗?
答案 0 :(得分:1)
在会话中设置。并且可以访问整个项目。
public function __construct()
{
parent::__construct();
$this->session->unset_userdata('site'); # unset on each and every time
$this->load->Model('settings_model');
$siteSettings = $this->settings_model->SiteSettings();
$this->session->set_userdata('site', $siteSettings); # Set after end of __construct
}
或者这样做
public function __construct()
{
parent::__construct();
$this->load->Model('settings_model');
$this->data['site'] = $this->settings_model->SiteSettings();
}
功能
$this->load->view("name",$this->data);