I have recently started using the CodeIgniter framework for my PHP development.
I was just curious as to correct usage.
Essentially I have the following situation.
I have a controller entitled ‘items’
I want it so if the user goes to items/index they get a list of caetgories, if they go to items/category-name they get a list of items.
To achieve this, I have the one controller with an if/elseif statement which loads different views. Is this the correct approach?
If i am on a items/category-name page, I load a view entitled ‘items-list’
I pass a variable entitled $type to this view.
In the view it detects this type (again with an if statement) and outputs the category title (also passed). Simple.
As well as this I have a completely different controller for a recently sold items list (dont ask :)). As the format of the list to display is essentially the same I utilize the same view, but pass a different $type var. The view detects this, outputs various ‘extra’ links, images etc and of course does not output a ‘categories’ title.
Essentially I have 2 controllers utilizing one view. With various if/elseif statements in both the controllers and the view to get the right output.
Is this the correct approach?
Thanks
In short…
there is no single right or wrong way to structure your controllers/views/models/libraries/helpers.
I too use CI, and I’ve found that controllers with the smallest amount of code in each controller method are the easiest to go back to and edit/maintain/upgrade/read. If too much logic is placed in my controller methods, clarity and understanding gets lost. I try to place most of my ‘logic’ in library or helper methods, so my controller methods are simple and easy to read.
I like to have the controller accept arguments/data, send it to models and/or library and helper methods, which return modified or new data. The returned data might get sent to other methods before finally being sent to a view.
This technique does tend to send you chasing around multiple files when writing an app or site, but achieves a clear separation of views and logic. Hopefully, it helps you write re-usable code too, even if it is only re-usable in the single app.
Whatever works for you and your team, is okay.