我的控制器中有一个函数比我希望的要长,我想重构它以调用一些离散函数以使其更易于管理。如何在 Codeigniter 控制器中更好地组织长函数?
我试过的:
我知道您可以通过使用前导下划线 (_myfunc) 命名它们来在控制器中创建私有函数,但是函数中的变量超出了调用控制器函数的范围。所以你必须从函数中返回所有需要的数据,这很麻烦。
这是管理复杂控制器功能的最佳选择吗?有没有更简单的方法,变量可以像标准类成员变量一样对控制器类都是全局的?
建议?提前致谢!
编辑:有人请求了代码,所以我在下面添加了巨型控制器的代码。改进的一个机会是将 switch 语句中的逻辑移动到单独的函数(删除、预览、排序等)。但我正试图在那之后决定下一步。将大型验证设置代码移到它自己的函数中确实会减轻一些负担,但是我应该将它移到哪里呢?
function categories() {
$this->load->library('upload');
$this->load->model('categories_m');
$this->load->model('products_m');
$this->load->model('pages_m');
$this->load->model('backoffice/backofficecategories_m');
$data['body'] = $this->load->view('backoffice/categories/navigation_v', '', TRUE);
$data['cat_tree'] = $this->categories_m->getCategoryTree();
$data['page_list'] = $this->pages_m->getPageList();
$data['category_dropdown'] = $this->load->view('backoffice/categories/category_dropdown_v',$data,TRUE);
switch ($this->uri->segment(3)) { //display views based on parameter in URL.
case 'delete':
$categoryTreeID = $this->sitewide_m->checkURLParam($this->uri->segment(4),'CategoryTree'); //if parameter is in URL, show 404 if invalid parameter is passed. Otherwise, set variable known to be safe.
if (isset($_POST['delete'])) {
$this->backofficecategories_m->deleteCategory($categoryTreeID);
$data['body'] .= '<span class="error">Category Deleted.</span>';
} else {
$data['cat_details'] = $this->categories_m->getCategoryDetails('',$categoryTreeID);
$data['parent_category'] = $this->categories_m->getParentCategory($categoryTreeID);
$data['products_to_reassign'] = $this->products_m->getProductsInCategory('',$categoryTreeID);
$data['body'] .= $this->load->view('backoffice/categories/delete_v',$data,TRUE); //pull fresh category tree data since tree was just updated.
}
break;
case 'preview':
if ($this->uri->segment(4)) $data['categoryTreeID'] = $this->sitewide_m->checkURLParam($this->uri->segment(4),'CategoryTree'); //if parameter is in URL, show 404 if invalid parameter is passed. Otherwise, set variable known to be safe.
$data['cat_details'] = $this->categories_m->getCategoryDetails(NULL,$data['categoryTreeID']); //get category ID being edited from the URL and store it. Returns false if category ID isn't found.
foreach ($data['cat_details']->result() as $detail) {
$data['categoryName'] = $detail->Name;
$data['categoryID'] = $detail->ID;
}
$data['body'] .= $this->load->view('backoffice/categories/preview_v', $data, TRUE);
break;
...cases continue...
default:
$this->load->library('table');
$data['body'] .= $this->load->view('backoffice/categories/categories_v', $data, TRUE);
break;
}
$this->load->view('backoffice/template_v',$data);
}