Okay, that goes back to complicating things.
Libraries should not have access to database. Fair enough, that means what I use as library should be a model. Then, back to the situation with the blog post. I have a post with various details. One of them being a category, the other an author. But, as these categories and authors have various details too, they're their own objects.
So when I want to display the post-content, I just do
echo $post->content; and be done with it. When I want to display the posts authors name, this would be
echo $post->author->name;.
Now I do this by using libraries. But, as said, I'm probably using libraries where I should be using models. My setup would then be something like this?
Code:
class Post_model extends CI_Model {
public $id;
public $title;
public $content;
public $category;
public $author;
public function get_data($postID) {
// Get the required Post
$result = $this->db->where('id', $postID)->get('posts');
// If result of query is 1 (should be only one post with that ID)
if($result->num_rows == 1) {
// Store the resulting row as... Object?
$post = $result->row(0, 'Post_model');
// And then comes the fun part. Create an empty Author,
// Call its get_data function and store the resulting object as
// this posts author
$author = new Author;
$post->author = $author->get_data($post->author);
// And the same goes for the category
$category = new Category;
$post->category= $category->get_data($post->category);
// All done? Then return this model
return $post;
}
}
}
Code:
class Category_model extends CI_Mode {
public $id;
public $name;
public $parent;
public function get_data($categoryID) {
// Get the required Category
$result = $this->db->where('id', $categoryID)->get('categories');
// If result of query is 1 (should be only one category with that ID)
if($result->num_rows == 1) {
// return the category as an object
return $result->row(0, 'Category_model');
}
}
}
// and the same for the user
So once I've done that, I can call my controller like
http://domain.com/blog/post/15, so my controller has the following method::
Code:
public function post($postID) {
// Create a new Post object
$post = new Post;
// Fill the object with data from id $postID (method-call)
$data['post'] = $post->get_data($postID);
// And send it to the view
$this->load->view('blogpost', $data);
}
Lean controller, fat model. Right?
I'm thinking I've been doing something terribly wrong all along...