Reputation: 4459
I have a variable that has the first URL segment. I want to use this as a class on the body
tag. It will mainly be used for setting links in my navigation as being active. Is there a way that I can create this variable in one place and use it in all of my controllers? Its not that big of a problem to set it in all of my controllers but I'd like to keep my code as clean as possible. This is what I have in my controllers right now:
$url_segment = $this->uri->rsegment_array(); //get array of url segment strings
$data['url_segment'] = $url_segment[1]; //gets string of first url segment
Is there a way to only have the code above ONCE in my app, instead of inside all of my controllers? If so where should I place it?
Upvotes: 0
Views: 215
Reputation: 1748
I'd extend CI_Controller
with a custom subclass that includes that variable, then have all the actual controllers extend that. CodeIgniter makes it easy - just create application/core/MY_Controller.php containing something along these lines:
class MY_Controller extends CI_Controller {
private $cached_url_seg;
function MY_Controller() {
parent::construct();
$url_segment = $this->uri->rsegment_array(); //get array of url segment strings
$this->cached_url_seg = $url_segment[1]; //gets string of first url segment
}
}
And then change your controllers to extend MY_Controller
.
You'll still have to add it to $data in each individual controller, but I suppose if you wanted you could add private $data
to MY_Controller
, too.
Upvotes: 3
Reputation: 1069
You might want to consider making a 1 time library file, with all features you want to be globally accessable, then in your autoload.php add this library there so it initializes automatically..
class my_global_lib {
protected $CI;
public $segment;
public function __construct(){
parent::__construct();
$this->CI =& get_instance();
// Do your code here like:
$this->segment = $this->CI->uri->segment(1);
// Any other things you want to have accessable by default could go here
}
}
This would allow you to call this from your controller like so
echo $this->my_global_lib->segment;
does this help?
Upvotes: 1