Question

I have seen a CodeIgniter application where the coder always protected table and fields at the tp of every model. Why would you do this? and maybe also why would you protect primary key separate from other fields?

class Students_model extends MY_Model{
    protected $table = 'students';
    protected $primary_key = 'id';
    protected $columns = array(                             
        'student_code'          =>  array('Code',    'trim|required'),
        'student_name'          =>  array('Name',    'trim|required'),
        'country'               =>  array('Country', 'trim|required'),                                  
    );
}
Était-ce utile?

La solution

This is a really good question for understanding best practices in MVC (not just Codeigniter). There are actually a few different things going on here.

1) "protected" is prolly done out of habit. This protected is the php class keyword, and has nothing to do with CI or Models. You can read about it here: http://jp2.php.net/protected; if after reading you don't understand why it is used in this case, it's because there really isn't a reason to use it in this case.

2) The key to understanding the rest is "extends MY_Model". MY_Model is a base model object where all your normal CRUD functions and utilities are written; we then inherit from it. However, our MY_Model will have a function like get_all() which will say:

$this->db->from($this->table)->get();

for example. So, in our Students model we set $this->table = "students", then the above code translates to:

$this->db->from('students')->get();  

but any other models can pass a different table name. So we are able to make very simple table specific models and share all the more complex logic via MY_Model

You can see that going back to #1, it is unlikely we'll ever inherit from Students_model, so protected isn't harming anything, but isn't terribly necessary

3) $columns in this case are the validation rules; whichever MY_Model being used here is also adding the validation functions to the MY_Model instead of putting on the controllers

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top