[eluser]Lone[/eluser]
Im not certain what is the best way to call the type of functions im about to talk about but I just wanted to see if anyone else does a similar method with their application development.
Example - Add a new product to website
Ok, so lets say we want to have a product manager on a site under which in the administration a user can see all of the products and add/edit products. Generally speaking we would have four functions in our controller to achieve this as below.
Please keep in mind this is a very very brief quick example.
Code:
function index() {
$data['products'] = $this->Product->get_all();
$this->load->view('products');
}
function add() {
$data['mode'] = 'add';
$data['product']['name'] = '';
$data['product']['description'] = '';
$this->load->view('product_addEdit'); // Has a form that submits to do_addEdit function
}
function edit() {
$data['mode'] = 'edit';
$data['product'] = $$this->Product->get($this->uri->segment(3));
$this->load->view('product_addEdit'); // Has a form that submits to do_addEdit function
}
function do_addEdit() {
if ($this->input->post('mode')=='add') {
// Add product functionality
} else if ($this->input->post('mode')=='edit') {
// Edit product functionality
}
redirect('products');
exit;
}
The key things from above are:
- Same view used for adding and editing a product
- When you submit the form to add/edit it's action url is set to a 'do_addEdit' function instead of itself
I am really preferring the building of controller functions like this as I feel it allows for better seperation of the viewing and creating/adding functionality (making it easier to read) and makes for smaller controller functions and helps follow the DRY principle a bit easier.
Does anyone else do their function building similar to our above approach or have any opinions on doing it this way?