如何在 CodeIgniter 中使用户对象跨页面可用?
我对 CodeIgniter 相当陌生,我正在使用 Ion Auth 进行用户授权。使用 Ion Auth 库,您可以获得一个用户对象,例如:
$user = $this->ion_auth->get_user();
echo $user->email;
如果用户登录,我希望 $user 对象在任何页面(在任何控制器中)上可用。我该怎么做? (我正在使用 CodeIgniter 2)
I'm fairly new to CodeIgniter and I'm using Ion Auth for user authorization. With the Ion Auth library, you get a user object like:
$user = $this->ion_auth->get_user();
echo $user->email;
If a user is logged in, I want the $user object to be available on any of the pages (in any of the controllers). How can I do this? (I'm using CodeIgniter 2)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的这篇博文涉及很多内容具体使用 Ion_Auth 来允许您的整个应用程序(包括视图)访问当前用户的信息的详细信息。
简短版本...(专门针对手头的主题)
将其添加到您的 MY_Controller.php 文件
然后在您的应用程序中只需创建这样的控制器
然后您不仅可以在您的控制器中访问
$this->the_user
但您还可以使用$this->load->vars()
将$the_user
加载到每个视图中>This blog post of mine goes into a lot of detail in specifically using Ion_Auth to allow your entire application (including views) to access your current user's information.
The short version... (specifically for the topic at hand)
Adding this to your
MY_Controller.php
fileThen in your application just create your controller like this
Then not only in your controller will you have access to
$this->the_user
but you will also have$the_user
loaded into every view with$this->load->vars()
通常,您会在会话中缓存类似的内容,但是我在大多数 CI 应用程序中都不再这样做。
一个例子:您登录用户(缓存用户数据),然后他们去更新他们的个人资料页面上的电子邮件。您现在必须重新加载缓存。许多其他因素可能会推动这种重新加载。通常我最多缓存的是 ID,然后我会执行您正在执行的操作并在我需要的任何页面上获取用户数据。
我发现有帮助的一件事是拥有基本控制器。例如我有一个 RegisteredUserController。任何其操作都需要用户登录的控制器都可以扩展此功能。这样我就可以保持登录检查以及诸如在一个位置(在构造函数中)获取用户数据之类的事情。例如:
那么任何扩展
RegisteredUserController
而不仅仅是控制器的控制器都可以通过$this->user
访问用户。遵循此模式将在每个页面(扩展控制器)上获取它,而无需诉诸缓存。Normally you'd cache something like this in the session, however I've moved away from that in most of my CI apps.
An example: you log the user in (caching the user data) and then they go to update their email on their profile page. You now have to reload you cache. Many other things could drive this reload. Usually the most I cache any more is the ID, then I do what you're doing and get the user's data on any page I need it.
One thing I found that helps is to have base controllers. For example I have a RegisteredUserController. Any controller whose actions all require the user to be logged in extend this. That way I can keep the logged in check and things like get the user data in one spot (in the constructor). For example:
Then any controller that extends
RegisteredUserController
instead of just controller can get to the user with$this->user
. Following this pattern would get it on every page (that extends the controller) without resorting to caching.