我的控制器中有一个功能,它的长度比我想要的要长,我想重构它来调用一些离散函数,以便更容易管理.如何在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'] .= 'Category Deleted.';
} 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);
}
小智.. 5
你在使用模特吗?代码点火器不会强制执行此操作,但除了控制器和视图之外还使用模型是控制器功能更短的好方法.或者,您可以将一些函数放在自己的帮助器中,然后导入它.
如果要为整个构造函数设置一些默认值,可以使用类构造函数.这在此概述:
http://codeigniter.com/user_guide/general/controllers.html#constructors
你在使用模特吗?代码点火器不会强制执行此操作,但除了控制器和视图之外还使用模型是控制器功能更短的好方法.或者,您可以将一些函数放在自己的帮助器中,然后导入它.
如果要为整个构造函数设置一些默认值,可以使用类构造函数.这在此概述:
http://codeigniter.com/user_guide/general/controllers.html#constructors