这是我的控制器我需要使用上面的三行作为全局变量。这样所有的函数都可以使用它。我该怎么做呢?
class Some_Controller extends CI_Controller {
$this->load->library('session'); //Must be global
$this->session->set_userdata('email', 'email@hp.com'); //Must be global
$data['current_user']=$this->session->userdata('email'); //Must be global
public function index(){
$data['people'] = $this->some_model->getPeople();
$data['mapList'] = $this->some_model->getMapped();
$data['appServList'] = $this->some_model->getApp_serv();
$this->load->view('templates/header.php',$data);
$this->load->view('some_page/index.php',$data);
/*Serves as the homepage. Shows the list for services, mapped services to an application and the list for application,
from here you can easily add edit and hide items*/
}
要自动启动会话,可以在autolload .php中设置$autoload['libraries'] = array('session');
。一旦你在session
中设置了一个数据,你就可以在任何你想要的地方使用它。要在会话中设置数据,您不需要全局地这样做,您可以在登录函数中这样做。之后在控制器当前位置放置public $current_email=$this->session->userdata('email');
并将current_email
访问为$this->current_emai;
。
访问视图中的变量,可以执行
$objCI =& get_instance(); //now CI object can be used
echo $objCI->current_email;
直接将变量声明为public
class Some_Controller extends CI_Controller {
//添加全局变量,可以被这个类中的所有函数使用。
public $global_variable = "global_example";
$this->load->library('session'); //Must be global $this->session->set_userdata('email', 'email@hp.com'); //Must be global
$data['current_user']=$this->session->userdata('email'); //Must be global
public function index(){
$data['people'] = $this->some_model->getPeople();
$data['mapList'] = $this->some_model->getMapped();
$data['appServList'] = $this->some_model->getApp_serv();
$this->load->view('templates/header.php',$data);
$this->load->view('some_page/index.php',$data);
/*Serves as the homepage. Shows the list for services, mapped services to an application and the list for application,
from here you can easily add edit and hide items*/
}
这里有两点值得注意:
第一个也是不相关的,您只需要在成功的身份验证过程之后才需要设置这样的会话数据,而不是每次都在通用控制器的顶部设置。
第二个也是最重要的一个,我理解你所说的全局变量。当你开始设计你的应用程序时,你会觉得需要多个类型的控制器。例如,您可能有Admin_Controller
、Backoffice_Controller
或Ajax_Controller
控制器。有些人可能会扩展其他人。所以当你说全局变量时,我认为你需要这样的机制。你在父控制器中设置一个变量它会在你应用的所有派生控制器中可用。我建议您创建一个Base_Controller
作为所有应用程序控制器的父控制器,该控制器包含所有其他应用程序的一般逻辑/数据。