Welcome Guest, Not a member yet? Register   Sign In
Controller code.. your opinion?

Hello there, i had a disscussion with my friend about code align in controllers. Consider these examples:

A) separate functions

function add_user() {
// code goes gere

function edit_user(){

function del_user(){

B) topic-related function

function user($action){
switch($action) {

case 'add':
// code goes here

case 'edit':

case 'del':

Which one is the better way how to organize code in controllers and why is that so?
Thx for answers Smile

[eluser]Adam Griffiths[/eluser]
I always use the first version, it's probably because when I used procedural code I had different files for each action, and it just stuck. I can see the benefits of having all the edit functions in one controller, for example.

Although it would get messy if you had a modular structure like I use now, which is why I stick with the first. But then again I would have the whole function in a model and just run it from the controller.

With CI I use the first one, but before I always used switches.

The first way makes you write code that is spread out more which makes it easier to eyes.
The second way you can look for code that is similar in the different actions and you can make it DRY.

I use the second way and put the code in the cases up to ten lines per case, if it's more i use methods so it's a third way Smile
function user($action)
      case 'add': break;
      case 'edit': $this->_edit(); break;
      case 'delete': break;

function _edit()


I use the first. Always. Personally, I think it's a better coding practice. I also think the first way is a tad faster. Not sure though.

I would use A as well. It seems to me to be easier to maintain specific functions than have larger switched functions. Besides, the whole point of object oriented programming is to group functions and variables into data types. Effectively giving you the badass version of method B.

Method A. No one has mentioned this, but using style A allows for very exact naming in both your functions and your urls if that matters.

Using style A as it is above, you can have nice clean urls like:


You get the idea. Using your imagination a little, CI becomes one heck of a search engine optimization tool since it allows you to craft how your urls will appear.

Joe you have to use routing with method A you have nice urls with method B

I did something similar today. I had a controller method for adding/editing records, using the same html form.

Bu I wanted urls like admin/edit and admin/new, so I did:
function record($id = NULL){
  // if $id == null then it's an add, else it's an edit

  // show the form etc

function add(){

function edit($id){

Keeps the code in one place but looks nice too!


sorry, see below

Theme © iAndrew 2016 - Forum software by © MyBB