Welcome Guest, Not a member yet? Register   Sign In
setting global value
#1

[eluser]louis w[/eluser]
What is the best way to set a variable inside your application to be shared throughout all the steps of a process? I would like to set it from within the controller and allow it to be accessed from the model, view, libraries and helpers.
#2

[eluser]gtech[/eluser]
why not use the session?
#3

[eluser]louis w[/eluser]
Do CI's sessions work just like the native php session? If i set a value, would it still be there on the user's next request (page load).
#4

[eluser]gtech[/eluser]
yes they do, the session variable is destroyed when the browser is closed or the session times out (which you can change by configuration)

the documentation is quite good

[url="http://ellislab.com/codeigniter/user-guide/libraries/sessions.html"]http://ellislab.com/codeigniter/user-guide/libraries/sessions.html[/url]
#5

[eluser]louis w[/eluser]
I would like for the variable to only persist durig the current request. Any other way besides session? Can you access variables from controller?
#6

[eluser]gtech[/eluser]
I seem to remember a $GLOBALS array you can use.


[url="http://ellislab.com/forums/viewthread/77607/"]http://ellislab.com/forums/viewthread/77607/[/url]

controller:
Code:
<?php
class Home extends Controller   {
  function Home(){
    parent::Controller();

    $GLOBALS['whatever'] = 'hello';
  }
  function index() {
    global $whatever;
    echo $whatever;

    $this->load->model('homem');
    $this->homem->getInfo();
  }
}
?>

model
Code:
<?php
class Homem extends Model {
    function __construct() {
        parent::Model();
    }
    
    function getInfo() {
      global $whatever;
      echo $whatever;
    }
}
?>

output:

hellohello
#7

[eluser]louis w[/eluser]
Interesting. Thanks.
#8

[eluser]Seppo[/eluser]
I really don't like working with globals... you can set it as a Controller attribute, and access it throught
Code:
$this->varname

inside your controller

Code:
$CI =& get_instance();
$CI->varname
everywhere else
#9

[eluser]gtech[/eluser]
yep you are right seppo, beat me to it.. this works just as well.
Code:
<?php
class Home extends Controller   {
  function Home(){
    parent::Controller();
    $this->whatever = 'hello';
  }
  function index() {
    echo $this->whatever;

    $this->load->model('homem');
    $this->homem->getInfo();
  }
}
?>

Code:
<?php
class Homem extends Model {
    function __construct() {
        parent::Model();
    }
    
    function getInfo() {
      echo $this->whatever;
    }
}
?>
#10

[eluser]louis w[/eluser]
Oooh. Nice, I guess i did not know the full power of get_instance. This will work perfectly.




Theme © iAndrew 2016 - Forum software by © MyBB