Spidy has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Fellow Monks,

Recently, I have been tasked with the creation of a system that relies on Perl/CGI and MySQL. It involves the creation of 4 entities within the database, all within different tables, with different attributes. Each of these 4 entries is 'commentable'; that is, users can write short, blogcomment-like comments in response to them. All of the entity comments follow the same template(comment author, content, title, etc...), but the entity attributes do not. I would like to write a script that will output the comments for each entity using exactly the same template. I know that this is possible, because the only variance in regards to commenting is the name of the MySQL table that the comment data is stored in. Does anyone know how I would accomplish this?



Thanks,
Spidy


Edit: I'd like something where I can provide a link like this:

And the system would be capable of growing, if I later needed to add another entity type.

Replies are listed 'Best First'.
Re: Pseudo-Polymorphism
by chromatic (Archbishop) on Sep 09, 2006 at 05:41 UTC

    If the comments all have the same structure, why store them in different tables? Create a comments table and link that to each of the other four tables somehow. (I suspect you need a linking table to make the one-to-many relationship work, but that's pretty standard.)

    Then all you need to do is use a templating system that allows you to use fragments or components and define a comment component and reuse that in your other templates.

      That's pretty much the idea I had, but I was a bit confused about the linking table thing. What do you mean by that, and how would I do it?
        Don't you just need a field called "parent_type" (or whatever) in the "Comments" table? You'd then be able to query all the comments, all the comments associated with one of the four tables, and (in conjuction with "parent_id") all the comments associated with a specific item in one of the four tables.

        In SQL, I would generally handle that something like this:

        CREATE TABLE entity_ones ( id INTEGER, -- whatever goes in this table ); CREATE TABLE entity_twos ( id INTEGER, -- whatever goes in this table ); CREATE TABLE comments ( id INTEGER, author VARCHAR(128), content TEXT, -- etc ); CREATE TABLE entity_one_comments ( entity_one_id INTEGER NOT NULL REFERENCES entity_ones(id), comment_id INTEGER NOT NULL REFERENCES comments(id), PRIMARY KEY ( entity_one_id, comment_id ) ); CREATE TABLE entity_two_comments ( entity_two_id INTEGER NOT NULL REFERENCES entity_twos(id), comment_id INTEGER NOT NULL REFERENCES comments(id), PRIMARY KEY ( entity_two_id, comment_id ) );

        We're not surrounded, we're in a target-rich environment!