Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialArash Emadi
10,002 PointsHow can I have a super global variable in CodeIgniter which is accessible in all my Controllers?
Hello. I've been developing a web app with CodeIgniter.
In my admin area, I want to know the Current User's info on every page and every controller.
How can I set this variable once and make all controllers know it and use it without actually writing the code inside every Controller? As of now, I have to introduce my $data['current_user'] variable inside all of my back-end variables. Example code below:
<?php
/**
* Admin Dashboard Class (INDEX)
*/
class Dashboard extends MY_Controller
{
// INDEX METHOD
public function index(){
// If Logged In Get Current User (Add to All Controllers)
$data['cuser'] = $this->User_model->get_user($this->session->userdata("user_id")->id);
// View
$data['main_content'] = 'admin/dashboard/index';
$this->load->view('admin/layouts/main', $data);
}
}
?>
1 Answer
miguelcastro2
Courses Plus Student 6,573 PointsCreate a base controller that all of your other controllers extend from. If in your base controller you have a property that stores the user's info, then all of the controllers which extend from the base controller will inherit the properties.
Example:
<?php
// Base controller which sets application wide properties.
class BaseController extends MY_Controller
{
protected $data = [];
public function __construct()
{
// Ensure you run parent constructor
parent::__construct();
$this->setUser();
}
public function setUser()
{
$this->data['cuser'] = $this->User_model->get_user($this->session->userdata("user_id")->id);
}
}
class Dashboard extends BaseController
{
public function __construct()
{
// Ensure you run parent constructor
parent::__construct();
}
public function index() {
// Access the data property using $this
$this->data['main_content'] = 'admin/dashboard/index';
$this->load->view('admin/layouts/main', $this->data);
}
}
?>
Now all of the controllers that extend BaseController will have the user info. This is very handy as you can also setup a lot of what you need throughout your application within your base controller and not repeat yourself in other controllers.