简体   繁体   中英

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.

<?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.

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

// put MY_Controller.php under core directory

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)

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 )

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:

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

$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.


Lets go to the example:

keep in mind that session is like 2d array (I work with 4+5d arrays myself)

$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

  1. well you need to pass some data to it first add_data($arr = array(), $data = ''){}

eg: 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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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