Reputation: 8705
I have several $data which are called in almost all functions in controller. Is there a way to create this $data in __construct function and combine them with $data in called function? Example:
function __construct() {
parent::__construct();
$this->load->model('ad_model', 'mgl');
$this->load->model('global_info_model', 'gi');
$this->load->model('user_model', 'um');
$this->load->library('global_functions');
$this->css = "<link rel=\"stylesheet\" href=\" " . CSS . "mali_oglasi.css\">";
$this->gi_cat = $this->gi->gi_get_category();
$this->gi_loc = $this->gi->gi_get_location();
$this->gi_type = $this->gi->gi_get_type();
}
function index() {
$count = $this->db->count_all('ad');
$data['pagination_links'] = $this->global_functions->global_pagination('mali_oglasi', $count, 2);
$data['title'] = "Mali Oglasi | 010";
$data['oglasi'] = $this->mgl->mgl_get_all_home(10);
$data['loc'] = $this->gi_loc;
$data['cat'] = $this->gi_cat;
$data['stylesheet'] = $this->css;
$data['main_content'] = 'mali_oglasi';
$this->load->view('template',$data);
}
If I want to put $data['loc'], $data['cat'] and $data['stylesheet'] in __construct I will have to call $this->data in $this->load->view('template',$data);
Is there a way to combine this two?
Upvotes: 0
Views: 356
Reputation: 35301
Sure, you could do it like this,
class ControllerName extends CI_Controller {
private $_data = array();
function __construct()
{
$this->_data['loc'] = this->gi_loc;
$this->_data['cat'] = this->gi_cat;
$this->_data['stylesheet'] = this->css;
}
function index()
{
// Your data
// Merge them before the $this->load->view();
$data = array_merge($this->_data, $data);
}
}
Upvotes: 2
Reputation: 197682
Add a private member to your controller and set it in the constructor as you need it:
private $data;
function __construct() {
...
$this->data = array(...);
...
}
Then you can access this private member in all of your controllers actions inside the same controller class.
You can merge two arrays using the array union operator (+
)Docs:
$data = $this->data + $data;
See as well: PropertiesDocs
Upvotes: 3