[eluser]Unknown[/eluser]
I am curious how others are coding controller functions that do one thing, but can be accessed through multiple methods. For the sake of example, imagine a controller for administrating categories.
1. You want to be able to delete categories via a
hyperlink that is captured by javascript and handled by an ajax request, with a JSON response.
2. In the interest of being degradable, you want the
hyperlink (something like "/admin/categories/delete/27") to be functional, in case javascript is turned off.
3. Elsewhere in the admin, you have a page that allows you to delete multiple categories or some other method that involves
posting the category_id.
The most obvious three techniques I can think of are included below, but they all seem a
bit clunky. How are you handing these types of situations in your controller code?
(These are all coded quickly for this post and not actually used, just a general idea...)
Possible Technique 1: One Function
Code:
function delete() {
if(intval($this->uri->segment(4))) {
$category_id = (int) $this->uri->segment(4);
$this->category_model->delete($category_id);
$this->load->view("admin/categories/delete_succes");
} else {
$category_id = (int) $this->input->post('category_id');
$this->category_model->delete($category_id);
if($this->user_agent->is_ajax()) {
$json = array(
"result" => "success",
"message" => "The category was successfully deleted."
);
$this->load->view("json", $json);
} else {
$this->load->view("admin/categories/delete_succes");
}
}
}
Possible Technique 2: Separate functions
Code:
function ajax_delete() {
$category_id = (int) $this->input->post('category_id');
$this->category_model->delete($category_id);
$json = array(
"result" => "success",
"message" => "The category was successfully deleted."
);
$this->load->view("json", $json);
}
function delete() {
$category_id = (int) $this->uri->segment(4);
$this->category_model->delete($category_id);
$this->load->view("admin/categories/delete_succes");
}
function post_delete() {
$category_id = (int) $this->input->post('category_id');
$this->category_model->delete($category_id);
$this->load->view("admin/categories/delete_succes");
}
Possible Technique 3: Utility Functions
Code:
function delete() {
if(intval($this->uri->segment(4))) {
$this->_process_delete($this->uri->segment(4));
} else {
$category_id = (int) $this->input->post('category_id');
if($this->user_agent->is_ajax()) {
$this->_process_ajax_delete($category_id);
} else {
$this->_process_delete($category_id);
}
}
}
Thanks in advance.