Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to controller's constructor

I have a controller which has several methods which should all share common informations. Let's say my URI format is like this:

http://server/users/id/admin/index
http://server/users/id/admin/new
http://server/users/id/admin/list
http://server/users/id/admin/delete

I need to retrieve some informations from the database for id and have them available for all methods instead of writing a line in each of them to call the model. How can I do this?

like image 376
Matteo Riva Avatar asked Dec 18 '09 12:12

Matteo Riva


1 Answers

class users extends Controller {

 private $mydata = array();

 function users()
 {   
     parent::Controller();
     ....

     $this->mydata = $this->model->get_stuff($this->uri->segment(2));
 }

 function index()
 { 
     $this->mydata; //hello data!
 }

Here I simply hardcoded the array (which probably is a really bad idea). Nevertheless you can store the data in a codeigniter session if you need to. Codeigniter can store this data in a cookie (if it's total is less than 4kb) otherwise you can store bigger blobs of data in the database (see the docs on how to do this).

See: http://codeigniter.com/user_guide/libraries/sessions.html

Subsection: Saving Session Data to a Database

Here's some session exercise:

$this->session->set_userdata('mydata', $mydata);
....
$mydata = $this->session->userdata('mydata');
like image 177
ascotan Avatar answered Oct 03 '22 09:10

ascotan