我是否应该从需要显示当前登录用户的一些详细信息的 header 中为我的 header 从 session 变量中获取一些数据。或者,在每个 Controller 中,加载用户数据然后将其发送到相应的 View ?似乎我应该从 Controller 中执行此操作,但将其放在 header 中需要更少的代码。
最佳答案
你应该吗?为了可维护性和尊重 MVC 模式,我会说在 Controller 中进行,我认为一行代码不会成为问题,你可以像这样得到它:
$data['userdata'] = $this->session->all_userdata(); // returns and associative array
然后将其传递给 View ,并使用 $userdata['whatever'] 在 View 中取出内容,这与从标题中获取它的代码量相同。
函数位于here
编辑 - 2015 年 11 月 3 日
截至version 3.0 $this->session->all_userdata();
已贬值。直接访问 $_SESSION
对象是首选方法,但是没有参数的 $this->session->userdata();
可以用于较旧的应用程序。
$data['userdata'] = $_SESSION; // returns and associative array
或
$data['userdata'] = $this->session->userdata();
有关 userdata() 的文档:
Gets the value for a specific
$_SESSION
item, or an array of all “userdata” items if not key was specified.NOTE: This is a legacy method kept only for backwards compatibility with older applications. You should directly access
$_SESSION
instead.
关于php - Codeigniter - 我应该在 View 中访问 session 数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7624256/