Structure CodeIgniter Application
I'd like to share my application structure here.
I start with model. I write 1 model for one table in the mysql database. I already have MY_Model
class that I put in system/application/libraries/
folder. This class have get_detail
, get_list
, get_total
, get_all
, insert
, update
, and delete
method. I store the table name in a var, so basically I just need this code in model to make it worked:
class Some_table_model extends MY_Model { function Some_table_model() { $this->tablename = 'some_table'; $this->primary_key = 'id'; }}
Update: after some more project, I have added new var to hold the column name used for primary key in the table. This way, I will have more flexibility by not hard coded the column name for primary key in MY_Model
.
For the controller, I create it according to it's usage by user. Example for a product, I will have this controller:
function Product extends Controller { function index() { //display product list, paginated } function admin() { //protected by session //display product list for admin, paginated //handle POST request to delete a product or products } function form() { //protected by session //handle add/edit product for admin }}
View is related to controller. For above controller, I will have at least 3 view file:
product_list.phpproduct_admin.phpproduct_form.php
View can be placed in subdir, for example, I can arrange it like this:
system/application/views/front/product.phpsystem/application/views/admin/product_list.phpsystem/application/views/admin/product_form.php
If product have category, I will need another table and model for it, but for controller, I can put the page inside Product controllers, by adding category into the function name:
function category_admin(){ //get parameter //... //process data //... //redirect or load view //...}function category_form(){ //get parameter //... //process data //... //redirect or load view //...}
That's what I do and it's work for me. Hope this help you find a better way to refactor your CodeIgniter's code.
should separate controller. but controller also change the url if you do not use router to alter it.
for Model, i usually map 1 controller to 1 model, if DB cost more than 4 lines.
First of all, model definately needs seperating to something like:
user_model: add_user(); delete_user(); ...products: add_product(); delete_product(); ...transaction: ... ...
you should get the idea.
Controller could do with some seperation as well. My controllers in this scenario would be.
products: add_product(); show_product(); get_product(); ...users: add_user(); delete_user(); ...
and so on.The reason for repeating same functions in controllers and models is that you can easily change model to access different database/data source and nothing beyond that needs changing.
Besides, there's absolutely no need to load product model when you're adding user for example.