I'm a very newbie on CodeIgniter, and while I go on I run into problems that, in the procedural coding, were easy to fix
The current issue is: I have this controller
class Basic extends Controller { function index(){ $data['title'] = 'Page Title'; $data['robots'] = 'noindex,nofollow'; $data['css'] = $this->config->item('css'); $data['my_data'] = 'Some chunk of text'; $this->load->view('basic_view', $data); } function form(){ $data['title'] = 'Page Title'; $data['robots'] = 'noindex,nofollow'; $data['css'] = $this->config->item('css'); $data['my_other_data'] = 'Another chunk of text'; $this->load->view('form_view', $data); } }
As you can see, some array items repeat over and over:
$data['title'] = 'Page Title'; $data['robots'] = 'noindex,nofollow'; $data['css'] = $this->config->item('css');
Isn't there a way to make them "global" in the controller, so that I have not to type them for each function? Something like (but this gives me error):
class Basic extends Controller { // "global" items in the $data array $data['title'] = 'Page Title'; $data['robots'] = 'noindex,nofollow'; $data['css'] = $this->config->item('css'); function index(){ $data['my_data'] = 'Some chunk of text'; $this->load->view('basic_view', $data); } function form(){ $data['my_other_data'] = 'Another chunk of text'; $this->load->view('form_view', $data); } }
Thnaks in advance!
In CodeIgniter 4, we have a folder like app/config/Constant. php so you can define a global variable inside the Constant. php file. After your index.
What you can do is make "class variables" that can be accessed from any method in the controller. In the constructor, you set these values.
class Basic extends Controller { // "global" items var $data; function __construct(){ parent::__construct(); // needed when adding a constructor to a controller $this->data = array( 'title' => 'Page Title', 'robots' => 'noindex,nofollow', 'css' => $this->config->item('css') ); // $this->data can be accessed from anywhere in the controller. } function index(){ $data = $this->data; $data['my_data'] = 'Some chunk of text'; $this->load->view('basic_view', $data); } function form(){ $data = $this->data; $data['my_other_data'] = 'Another chunk of text'; $this->load->view('form_view', $data); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With