简体   繁体   English

Codeigniter中的全局数据数组

[英]Global data array in Codeigniter

I have an array like this 我有这样的数组

  $meta = array(
       'meta_description' => 'lorem ipsum',
       'meta_keywords' => 'this, is, a, keyword'
  );

If I have this in my controller method, I can pass it to a partial like so: $this->template->set_partial('header', 'layouts/header', $meta) and it passes fine. 如果我在控制器方法中有此选项,则可以将其传递给这样的局部$this->template->set_partial('header', 'layouts/header', $meta)$this->template->set_partial('header', 'layouts/header', $meta)并且它可以正常运行。

I store the meta tags in the database, so I'd ideally like to put it in MY_Controller and populate the array based on the database values for that post's meta tags. 我将meta标签存储在数据库中,因此理想情况下,我希望将其放在MY_Controller中,并根据该帖子的met​​a标签的数据库值填充数组。

If I move it outside of the controller method, I get Message: Undefined variable: meta as an error. 如果将其移出控制器方法之外,则会收到Message: Undefined variable: meta作为错误。

How can I make it globally available? 如何使其在全球范围内可用?

I think I figured it out. 我想我知道了。

I just created a new model for handling meta data, then I insert the following into MY_Controller's construct method: 我刚刚创建了一个用于处理元数据的新模型,然后将以下内容插入MY_Controller的Construct方法:

 $meta = $this->meta_data_model->get_item_meta();

 $this->template->set_partial('header', 'layouts/header', $meta);

This seems to work fine, not sure if there is a better way of doing it. 这似乎很好用,不确定是否有更好的方法。

Anything you want to access globally should be stored in the user session: 您要全局访问的所有内容都应存储在用户会话中:

$this->load->library('session'); // Unless auto loaded
$this->session->set_userdata('meta', $meta);

Then retrieve it where you need it: 然后在需要的地方检索它:

$meta = $this->session->userdata('meta');

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

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