[英]How to pass the data to view in codeigniter
假设我有一个像这样的叫家的控制器
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()上的数据库中获取数据,并在我调用其他方法时将值传递给每个方法。
我怎样才能做到这一点? 我是否应该使用公共变量并将获取的数据存储到此变量,然后从其他方法调用该变量?
在会话中进行设置。 并可以访问整个项目。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.