Prerequisites
ccdn-forum/karma-bundle to composer.json:
composer require ccdn-forum/karma-bundle
Bundle Registration
Add to app/AppKernel.php:
new CCDN\ForumBundle\KarmaBundle(),
Database Migrations
Run Doctrine migrations (if included in the bundle) or manually create the karma table:
CREATE TABLE karma (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
user_id INT NOT NULL,
rating TINYINT NOT NULL, -- +1 or -1
comment TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES forum_posts(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
First Use Case Display a "Rate Post" button in your forum template:
{% if is_granted('ROLE_USER') %}
{{ path('ccdn_forum_karma_rate', { postId: post.id }) }}
{% endif %}
Rating a Post
POST route /forum/karma/rate/{postId} with form data:
// Controller action (example)
public function rateAction(Request $request, $postId) {
$rating = $request->request->get('rating'); // +1 or -1
$comment = $request->request->get('comment');
$this->get('ccdn_forum.karma.manager')->ratePost($postId, $rating, $comment);
return new RedirectResponse($request->headers->get('referer'));
}
Displaying Karma
{% set karma = karma(post) %}
<div class="karma-score">
{{ karma.score }} -- {{ karma.votes }} votes
</div>
Integration with ForumBundle
ForumPost entity to include karma methods:
// In your ForumPost entity
public function getKarmaScore() {
return $this->getKarmaManager()->getPostScore($this->id);
}
Form Handling
Use the bundle’s built-in form type (CCDN\ForumBundle\KarmaBundle\Form\Type\KarmaType) for rating forms:
$form = $this->createForm(KarmaType::class, $post, [
'action' => $this->generateUrl('ccdn_forum_karma_rate', ['postId' => $post->id])
]);
Event Listeners Trigger actions post-rating via events (e.g., update user reputation):
// In services.yml
ccdn_forum.karma.listener:
class: AppBundle\EventListener\KarmaListener
tags:
- { name: kernel.event_listener, event: ccdn_forum.karma.rated, method: onKarmaRated }
API Access Expose karma data via API (e.g., FOSRestBundle):
# config_routing.yml
ccdn_forum_karma_api:
path: /api/forum/post/{id}/karma
defaults: { _controller: CCDN\ForumBundle\KarmaBundle\Controller\ApiController::getKarma }
Missing Dependencies
Class 'CCDN\ForumBundle\ForumBundle' not found.CCDNForumForumBundle is installed and registered before KarmaBundle.Database Schema Mismatch
Column 'rating' not found or Foreign key constraint fails.karma table structure matches the bundle’s expectations (see Getting Started).Permission Issues
// src/Acme/ForumBundle/Security/Voter/KarmaVoter.php
public function supportsAttribute($attribute) {
return $attribute === 'rate_post';
}
Bootstrap CSS/JS Conflicts
{% block stylesheets %}
{{ parent() }}
{% if not app.hasBootstrap %}
{{ asset('bundles/ccdnforum/css/bootstrap.css') }}
{% endif %}
{% endblock %}
Enable Doctrine Logging
Add to config.yml to debug queries:
doctrine:
dbal:
logging: true
Check Event Dispatching Verify events fire by subscribing a debug listener:
public function onKarmaRated(KarmaEvent $event) {
error_log("Karma rated: " . print_r($event->getData(), true));
}
Custom Rating Logic Override the rating manager:
# services.yml
ccdn_forum.karma.manager:
class: AppBundle\Service\CustomKarmaManager
parent: ccdn_forum.karma.manager
Add Rating Categories
Extend the Karma entity to support multiple rating types (e.g., "helpfulness," "clarity"):
// src/AppBundle/Entity/Karma.php
class Karma extends CCDN\ForumBundle\KarmaBundle\Entity\Karma {
private $category;
}
Localization Translate rating labels (e.g., "Upvote," "Downvote") by overriding Twig templates:
{# templates/CCDNForumKarmaBundle/Karma/rate.html.twig #}
{% trans %}Upvote{% endtrans %}
Rate Limiting Prevent spam by adding a rate-limit service:
public function canRate($userId, $postId) {
$lastRating = $this->em->getRepository('CCDNForumKarmaBundle:Karma')
->findBy(['user_id' => $userId, 'post_id' => $postId], ['created_at' => 'DESC']);
return !$lastRating || (time() - $lastRating[0]->getCreatedAt()->getTimestamp() > 86400); // 24h cooldown
}
How can I help you explore Laravel packages today?