Object-oriented design question

Let’s say I have two objects that map in CRUD fashion to two database tables that are in a one-to-many relationship. A good example would be blog posts and comments. A blog post can have many comments, but a comment can only refer to one blog post.

Given this scenario, what’s the best way to get an array of Comment objects for a specific post?

Should the Post class have a method that returns the array of Comment objects or should the Comment class have a class method that returns the array of Comment objects (based on a post id parameter)? Or neither? Or both? Or it depends?

The former seems to me to be most immediately natural:

$comments = $post->getComments();

as compared to the latter:

$comments = Comment::byPostId($post_id);

The former also seems more consistent with a corresponding method I’d imagine would exist in the Comment class to fetch its parent post:

$post = $comment->getPost();

However, the latter design does have one benefit in that the SQL for accessing comment records can all be conveniently located in the Comment class. This is helpful if our child Comment class has more than one type of parent. Rather than implementing getComments() methods in several different objects (and thus files), they can all live together in the Comment class, e.g.

$comments = Comment::byPostId($post_id);
$comments = Comment::byAuthorId($author_id);

It also occurs to me that implementing getComments() in the Post class means that I have to first instantiate the post to get its comments. I might already have the post object I want laying around, but if not, that means another call to the database.

Thoughts? Suggestions?

comments: 1 so far...

name
blog (optional)
comment

I think $post->getComments() is best because it fits into your most likely context. You’ll probably be displaying a single post or a list of posts and already have that object available.

This is really an Object Relational Mapping question. Most ORM implementations (read Rails) have it so that every object knows which objects it’s related. So if you happened to have a $comment object you could write $comment->post and get back the right thing.

I believe Class::DBI is a perl module that will do most of this for you.

monthchunks

license

Justinsomnia is licensed under a Creative Commons Attribution 3.0 License.

Please see my Attribution Policy for more information.