简体   繁体   English

codeigniter中的动态全局数组

[英]Dynamic global array in codeigniter

I want a global array that I can access through controller functions, they can either add or delete any item with particular key. 我想要一个可以通过控制器功能访问的全局数组,他们可以使用特定键添加或删除任何项目。 How do I do this? 我该怎么做呢? I have made my custom controller ' globals.php ' and added it on autoload library. 我已经制作了自定义控制器' globals.php '并将其添加到自动加载库中。

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  $notification_array = array();
  $config['notification'] = $notification_array;
?>

following function on controller should add new item to my array 控制器上的以下函数应该将新项添加到我的数组中

function add_data(){
   array_unshift($this->config->item('notification'), "sample-data");
}

after add_data adds to the global array, whenever following function is called from client, it should give the updated array to the client. 在add_data添加到全局数组之后,每当从客户端调用以下函数时,它应该将更新的数组提供给客户端。

function send_json()
{
   header('content-type: application/json');
   $target = $this->config->item('notification');
   echo json_encode($target);
}

But my client always gets empty array. 但我的客户端总是得到空数组。 How can I make this happen? 我怎样才能做到这一点? Please help. 请帮忙。

Hi take advantage of OOP, like this 嗨利用OOP,像这样

// put MY_Controller.php under core directory //将MY_Controller.php放在核心目录下

class MY_Controller extends CI_Controller{

  public $global_array = array('key1'=>'Value one','key2'=>'Value2'):

   public function __construct() {
        parent::__construct();
    }

}

//page controller //页面控制器

class Page extends MY_Controller{

public function __construct() {
            parent::__construct();
        }

function send_json()
{
   header('content-type: application/json');
   $target = $this->global_array['key1'];
   echo json_encode($target);
}

}

One solution I came up is to use session, its easy to use and its "fast" you need to do some benchmarking. 我提出的一个解决方案是使用会话,它易于使用,而且“快速”需要进行一些基准测试。

As I commented on both answers above/below there is no way you get same data in different controllers just because with each request everything is "reset", and to get to different controller you need to at least reload tha page. 正如我对上面/下面的两个答案所评论的那样,你不可能在不同的控制器中获得相同的数据,因为每个请求都被“重置”,并且要到达不同的控制器,你至少需要重新加载页面。 (note, even AJAX call makes new request) (注意,即使是AJAX调用也会提出新请求)

Note that sessions are limited by size, you have a limit of 4kb (CodeIgniter stores session as Cookie) but wait, there is way around, store them in DB (to allow this go to config file and turn it on $config['sess_use_database'] = TRUE; + create table you will find more here ) 请注意,会话受大小的限制,您有4kb的限制(CodeIgniter将会话存储为Cookie)但等待,有办法将它们存储在DB中(允许这个转到配置文件并将其打开到$config['sess_use_database'] = TRUE; +创建表格,你会在这里找到更多)

Well lets get to the answer itself, as I understand you tried extending all your controllers if no do it and place some code in that core/MY_Controller.php file as follows: 好吧,让我们得到答案本身,据我所知你尝试扩展所有控制器,如果没有这样做,并在核心/ MY_Controller.php文件中放置一些代码,如下所示:

private function _initJSONSession() { //this function should be run in MY_Controller construct() after succesful login, $this->_initJSONSession(); //ignore return values

    $json_session_data = $this->session->userdata('json');

    if (empty($json_session_data )) {

    $json_session_data['json'] = array(); //your default array if no session json exists,
                                          //you can also have an array inside if you like

        $this->session->set_userdata($ses_data);
        return TRUE; //returns TRUE so you know session is created
    }

return FALSE; //returns FALSE so you know session is already created

}

you also need these few functions they are self explainatory, all of them are public so you are free to use them in any controller that is extended by MY_Controller.php, like this 你还需要这几个函数,它们是自我解释的,所有这些函数都是公共的,所以你可以在任何由MY_Controller.php扩展的控制器中自由使用它们,就像这样

$this->_existsSession('json');

public function _existsSession( $session_name ) {

    $ses_data = $this->session->userdata( $session_name );

    if (empty( $ses_data )) return FALSE;

    return TRUE;

}

public function _clearSession($session_name) {

    $this->session->unset_userdata($session_name);

}

public function _loadSession($session_name) {

    return (($this->_existsSession( $session_name )) ? $this->session->userdata($session_name) : FALSE );

}

the most interesting function is _loadSession() , its kind of self explainatory it took me a while to fully understand session itself, well in a few words you need to get (load) data that are in session already, do something with it ([CRUD] like add new data, or delete some) and than put back ( REWRITE ) all data in the same session. 最有趣的函数是_loadSession() ,这种自我解释我花了一段时间来完全理解会话本身,好几句话你需要得到(加载)会话中的数据,用它做一些事情([ CRUD]喜欢添加新数据,或删除一些),而不是将所有数据放回( REWRITE )同一会话中。


Lets go to the example: 让我们举个例子:

keep in mind that session is like 2d array (I work with 4+5d arrays myself) 请记住,会话就像2d数组(我自己使用4 + 5d数组)

$session['session_name'] = 'value';

$session['json'] = array('id' => '1', 'name' => 'asok', 'some_array' => array('array_in_array' => array()), 'etcetera' => '...');

so to write new ( rewrite ) thing in session you use 所以在你使用的会话中写新( 重写 )的东西

{
    $session_name = 'json';

    $session_data[$session_name] = $this->_loadSession($session_name);

    //manipulate with array as you wish here, keep in mind that your variable is
    $session_data[$session_name]['id'] = '2'; // also keep in mind all session variables are (string) type even (boolean) TRUE translates to '1'

    //or create new index
    $session_data[$session_name]['new_index'] = FALSE; // this retypes to (string) '0'

   //now put session in place

    $this->session->set_userdata($session_data);

}

if you like to use your own function add_data() you need to do this 如果你想使用自己的函数add_data()你需要这样做

  1. well you need to pass some data to it first add_data($arr = array(), $data = ''){} 你需要先将一些数据传递给它add_data($arr = array(), $data = ''){}

eg: array_unshift( $arr, $data ); 例如: array_unshift( $arr, $data );

{
    //your default array that is set to _initJSONSession() is just pure empty array();  

    $session_name = 'json';        
    $session_data[$session_name] = $this->_loadSession( $session_name );

    // to demonstrate I use native PHP function instead of yours add_data()
    array_unshift( $session_data[$session_name], 'sample-data' );

    $this->session->set_userdata( $session_data );
    unset( $session_data );
}

That is it. 这就对了。

You can add a "global" array per controller. 您可以为每个控制器添加“全局”数组。

At the top of your controller: 在控制器的顶部:

public $notification_array = array();

Then to access it inside of different functions you would use: 然后在您将使用的不同函数内访问它:

$this->notification_array;

So if you want to add items to it, you could do: 因此,如果您想向其中添加项目,您可以执行以下操作:

$this->notification_array['notification'] = "Something";
$this->notification_array['another'] = "Something Else";

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

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