In the CodeIgniter User Guide, the example model had an attribute for each field in the corresponding database table:
class Blogmodel extends CI_Model {
var $title = '';
var $content = '';
var $date = '';
//...
However when it returns a set of blog posts, they are only generic object.
function get_last_ten_entries()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
If each blog post is only going to be a generic object, what is the purpose of the attributes at the beginning of the class?
It seems like it would be nice to have each blog post as a fully fledged model
object populated with it's content. Then you could write methods that fetched
values internally. However, all the examples in the User Guide seem to show each
controller having one instance of each model and using that object to fetch
generic objects containing the database values. Additionally, the way the
examples instantiate the models ($this->load->model('Blog');
) it's clear that
you are only expected to have one instance of the model within the controller.
If my blog post has a status
value which is stored in the
database as an integer, but in several different controllers I want to show that
value as a human readable string, where do I put that function/method? Since I need it
in multiple controllers, and it's specific to one object, I assume it should be
a method of the model object. If each blog post is an instance of the model, I
could write it like this:
function get_human_status()
{
$lookup = array(
1 => 'Active',
2 => 'Hidden',
3 => 'Pending');
return $lookup[$this->status];
}
However, if each blog post is a generic object it would have to look like this:
function get_human_status($data)
{
$lookup = array(
1 => 'Active',
2 => 'Hidden',
3 => 'Pending');
return $lookup[$data->status];
}
Which way is the more idiomatic of CodeIgniter? Assuming it's the second, why does the example model define those internal attributes?
Finally, for bonus points, if I had other questions of this nature, what books, articles, or examples should I be looking at?