简体   繁体   English

CodeIgniter中的全局变量

[英]Global Vars in CodeIgniter

I want to save some global vars to use in the website, like current user id, current user lever, and so on. 我想保存一些全局变量用于网站,如当前用户ID,当前用户杠杆等。 Where is the best place to do it, or is it possible? 哪个地方最好,或者可能吗?

Setting it into constants.php is not working since "$this" is not recognized there. 将其设置为constants.php无法正常工作,因为“$ this”在那里无法识别。

The principal reason why I want this is because i don't like using sessions (I consider writing strings like $this->session->userdata('session_name') not so practical, writing something like CURR_UID is more easy to do it and read as well) 我想要这个的主要原因是因为我不喜欢使用会话(我考虑编写像$this->session->userdata('session_name')这样的字符串不那么实用,写一些像CURR_UID更容易做到这一点阅读也)

What you can do in this case is create a class My_Controller extends CI_Controller . 在这种情况下你可以做的是创建一个class My_Controller extends CI_Controller Sort out all the functionality that you would need before actually loading any of the specific controller functionality. 在实际加载任何特定控制器功能之前,整理出您需要的所有功能。

Then any subsequent class you create you can do: class Whatever extends My_Controller . 然后你创建的任何后续类都可以: class Whatever extends My_Controller

Edit: I forgot to mention you should put the My_Controller class within the Application > Core folder. 编辑:我忘了提到你应该将My_Controller类放在Application> Core文件夹中。

It's possible, but it isn't the way that Codeigniter was designed. 这是可能的,但它不是Codeigniter的设计方式。 Sessions are really the place for this kind of thing (namely, stuff that persists from one page view to the next), but you could wrap the session calls up in a library for beauty's sake if you wanted. 会话真的是这种事情的地方(即从一个页面视图到下一个页面视图持续存在的东西),但是如果你愿意的话,你可以将会话调用包装在一个库中。 Something like this: 像这样的东西:

// in libraries/User.php
class User {

  protected $ci;

  public function __construct() {
    $this->ci = &get_instance();
  }

  public function id() {
    return $this->ci->session->userdata('user_id');
  }

  // etc, etc.
}

Once you've written a few more helpers like id() , you can use them to access the relevant variables elsewhere in your application: 一旦你编写了一些像id()这样的帮助器,你就可以使用它们访问应用程序中其他地方的相关变量:

$this->load->library('user');
echo 'Current user ID is: ' . $this->user->id();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM