I am working on a basic blog application with Codeigniter 3.1.8 and Bootstrap 4.
In my Posts controller I have three methods that repeat 7 lines of code instead of sharing them:
public function index() {
// More code here
/* This code is in all three methods */
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['number_of_pages'] = $this->Pages_model->count_pages();
$data['number_of_posts'] = $this->Posts_model->get_num_rows();
$data['number_of_categories'] = $this->Categories_model->get_num_rows();
$data['number_of_comments'] = $this->Comments_model->get_num_rows();
/* This code is in all three methods */
$data['posts'] = $this->Posts_model->get_posts($limit, $offset);
$data['offset'] = $offset;
$this->load->view('partials/header', $data);
$this->load->view('dashboard/posts');
$this->load->view('partials/footer');
}
public function create() {
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['number_of_pages'] = $this->Pages_model->count_pages();
$data['number_of_posts'] = $this->Posts_model->get_num_rows();
$data['number_of_categories'] = $this->Categories_model->get_num_rows();
$data['number_of_comments'] = $this->Comments_model->get_num_rows();
$data['tagline'] = "Add New Post";
// More code here
}
public function edit($id) {
// More code here
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['number_of_pages'] = $this->Pages_model->count_pages();
$data['number_of_posts'] = $this->Posts_model->get_num_rows();
$data['number_of_categories'] = $this->Categories_model->get_num_rows();
$data['number_of_comments'] = $this->Comments_model->get_num_rows();
$data['post'] = $this->Posts_model->get_post($id);
}
I do not believe it is "effective" to create a base controller that extend the CI_Controller and then make all my controllers extend my base controller, as this base controller is related only to the posts.
What is the best alternative to creatibg a base controller in this case?