Codeigniter - 我应该在视图中访问会话数据吗?

发布于 2024-12-07 18:13:55 字数 112 浏览 2 评论 0原文

我是否应该从标题中为我的标题获取一些数据,该标题需要显示当前登录用户的一些详细信息。或者,在每个控制器中,加载用户数据,然后将其发送到相应的视图?似乎我应该从控制器中执行此操作,但将其放在标头中需要更少的代码。

Should I grab some data from a session variable for my header from the header which needs to display a few details for the user currently logged in. Or, in each controller, load user data then send it to the corresponding view? Seems like I should do it from the controllers but having it in header requires less code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回眸一笑 2024-12-14 18:13:55

你应该吗?为了可维护性和尊重 MVC 模式,我会说在控制器中执行此操作,我不认为一行代码会成为问题,您可以像这样获取所有内容:

$data['userdata'] = $this->session->all_userdata(); // returns and associative array

然后将其传递给视图,并使用 $userdata['whatever'] 在视图中获取内容,这与从标头获取内容的代码量相同。

该函数位于此处


编辑 - 2015 年 11 月 3 日

版本 3.0 $this->session->all_userdata(); 已被折旧。相反,直接访问 $_SESSION 对象是首选方法,但是不带参数的 $this->session->userdata(); 可以与旧应用程序一起使用。

$data['userdata'] = $_SESSION; // returns and associative array

$data['userdata'] = $this->session->userdata();

有关 userdata() 的文档:

获取特定$_SESSION项的值,或所有项的数组
如果未指定键,则为“userdata”项。

注意:这是一种遗留方法,仅用于向后兼容旧应用程序。您应该直接访问 $_SESSION

Should you? For the sake of maintainability and honoring the MVC pattern, I would say do it in the controller, I don't think one line of code is going to be an issue, you can get it all like this:

$data['userdata'] = $this->session->all_userdata(); // returns and associative array

Then pass that to the view, and get the stuff out in the view with $userdata['whatever'] which is the same amount of code as getting it from the header anyway.

The function is located here


Edit - 03 November 2015

As of version 3.0 $this->session->all_userdata(); has been depreciated. Instead directly accessing the $_SESSION object directly is the prefered method, however $this->session->userdata(); with no parameters could be used with older applications.

$data['userdata'] = $_SESSION; // returns and associative array

or

$data['userdata'] = $this->session->userdata();

Documentation on 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文