Controller code.. your opinion? |
[eluser]ok3x[/eluser]
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 break; case 'edit': break; case 'del': break; } } Which one is the better way how to organize code in controllers and why is that so? Thx for answers
[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.
[eluser]dpgtfc[/eluser]
With CI I use the first one, but before I always used switches.
[eluser]xwero[/eluser]
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 Code: function user($action)
[eluser]Bramme[/eluser]
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.
[eluser]textnotspeech[/eluser]
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.
[eluser]SitesByJoe[/eluser]
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: http://mydomain.com/users http://mydomain.com/users/add http://mydomain.com/users/edit http://mydomain.com/users/delete 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.
[eluser]xwero[/eluser]
Joe you have to use routing with method A you have nice urls with method B
[eluser]meigwilym[/eluser]
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: Code: function record($id = NULL){ Keeps the code in one place but looks nice too! Mei
|
Welcome Guest, Not a member yet? Register Sign In |