The goal of every programmer is to write as little code as possible. It can only be achieved by re-using code that you already wrote. That is why we all use CakePHP in the first place right? Fortunately, cake allows us to create plug-ins that we could just drop in into our projects and be done with it.
For quite a few of our projects, especially social applications, we had to add commenting. In addition, we typically had to allow users to comment on everything (photos, posts, news, articles, etc…). Here is the solution we came up with that worked very well:
1. Create comments table
create table comments ( id int unsigned not null auto_increment, model varchar(255) not null, foreign_key int unsigned not null, comment text not null, created datetime, creator_id int unsigned, modified datetime, modifier_id int unsigned, primary key(id), foreign key(creator_id) references users(id), foreign key(modifier_id) references users(id) )Engine=InnoDB;
Please note that this example assumes that you already have users table created. On how to set creator_id and modifier_id automatically please refer to the previous post by us called “Automagically setting user ID of record creator and modifier in CakePHP 1.2”
‘model’ and ‘foreign_key’ field will be used to identify which model the comment belong to.
2. Unzip the plugin code (comments_plugin.zip) into your cake’s plugin directory.
3. Go to the view where you want to attach your comments to. Insert the following line where the comments are suppose to appear:
<?php echo $this->requestAction('/comments/index/<ModelName>/<ModelId>', array('return')); ?>
requestAction? Hmm… You probably were told not to use it ever and that it’s evil. But in actuality it’s not harmful at all if used in moderate amounts ( as like everything else in life…). The moderate use of requestAction and the ease of management of you app will outweigh the slowness cause by the use of it.
And that’s it. You are done.
Please note that this plugin works very nicely with our jQuery Ajax helper