3

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.

7
  • 3
    please, forget about global variables, you are in OOP extend your controller class and declare your "global variable" there, you can acces it from any controller that is extended by it. Tutorial is here. Commented Sep 18, 2013 at 16:54
  • 1
    No problem, if you have troubles with it comment here again. Commented Sep 18, 2013 at 17:17
  • Well I've made array global, but it seems I cannot add another item I tried $this->global_array['mykey']="Ashok"; on add_data() function, but when I display the global_array, I don't have this new item. Commented Sep 18, 2013 at 18:04
  • Try array_push(), and print it out var_dump($variable). Please also note that any function in MY_Controller.php is avalible thru $this->function(); so you can have your send_json declared in MY_Controller, but call it in (imaginable) about controller. Commented Sep 18, 2013 at 18:54
  • 1
    Yey, but if you "reload" / "refresh" page every data/$variables (except that are in DB, file, session, cookies) are "lost", are you sure you have the right concept? You need to go thru your code read it "line by line" if there is a change in URL and you call different methods do not except same PHP variables. Every time you refresh/reload/send new GET || POST request you call constructors etc. Data that stay are just that in DB/Files etc. I am saying exactly same as @umefarooq in his comment. You need session to do this I guess. Commented Sep 19, 2013 at 8:31

3 Answers 3

1

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);
}

}
Sign up to request clarification or add additional context in comments.

7 Comments

I can access the $global_array, but how to add another item to it from add_data function so that the value will be persistent and can be accessed anytime later with send_json function?
if you are calling add_data with in send_json then it will be persistent, because with each call of controller you will get only default values
Well I cannot do that, there are other functions too, that can change the array. send_json should send the latest array, not default. how is it possible??
go for session but if yo will use this with login, on logout whole session will flush out, or when session expired then too, in that case you have to check in MY_Controller if session don't have value set your default define values.
not really, you just need to delete the session that you use, I do this all the time, see my answer. You just delete "desired" session variable.
|
1

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.

Comments

0

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

1 Comment

This is right answer I think in a way he needs only one controller + data, just because if he uses "MY_Controller" that extends his all controllers there is no way he is going to get same data (in different controller), just because everytime controller is called default array is set to begin with. He needs some persistant solution like session/cookies/files/database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.