【发布时间】:2019-12-21 10:40:27
【问题描述】:
我正在使用 Codeigniter 3.1.8 和 Bootstrap 4 开发一个基本的博客应用程序。
在我的 Posts 控制器中,我有三种方法可以重复 7 行代码,而不是 共享 它们:
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);
}
我不认为创建一个扩展 CI_Controller 的基本控制器然后使 所有我的控制器扩展我的基本控制器是“有效的”,因为这个基本控制器仅与帖子。
在这种情况下,创建基本控制器的最佳替代方案是什么?
【问题讨论】:
-
创建一个使用您的常用属性填充数据的方法?
标签: php codeigniter controller