Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Karma Bundle Laravel Package

ccdn-forum/karma-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup Steps

  1. Prerequisites

    • Install CCDNForumForumBundle first (this bundle depends on it).
    • Ensure Symfony 2.0.x and PHP 5.3.6+ are installed.
    • Add ccdn-forum/karma-bundle to composer.json:
      composer require ccdn-forum/karma-bundle
      
  2. Bundle Registration Add to app/AppKernel.php:

    new CCDN\ForumBundle\KarmaBundle(),
    
  3. 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)
    );
    
  4. 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 %}
    

Implementation Patterns

Core Workflows

  1. Rating a Post

    • Use the 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'));
      }
      
  2. Displaying Karma

    • Fetch karma for a post in a Twig template:
      {% set karma = karma(post) %}
      <div class="karma-score">
          {{ karma.score }}  -- {{ karma.votes }} votes
      </div>
      
  3. Integration with ForumBundle

    • Extend ForumPost entity to include karma methods:
      // In your ForumPost entity
      public function getKarmaScore() {
          return $this->getKarmaManager()->getPostScore($this->id);
      }
      

Common Patterns

  • 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 }
    

Gotchas and Tips

Pitfalls

  1. Missing Dependencies

    • Error: Class 'CCDN\ForumBundle\ForumBundle' not found.
    • Fix: Ensure CCDNForumForumBundle is installed and registered before KarmaBundle.
  2. Database Schema Mismatch

    • Error: Column 'rating' not found or Foreign key constraint fails.
    • Fix: Manually verify the karma table structure matches the bundle’s expectations (see Getting Started).
  3. Permission Issues

    • Error: Users can rate posts without checks.
    • Fix: Implement custom voters or extend the bundle’s security logic:
      // src/Acme/ForumBundle/Security/Voter/KarmaVoter.php
      public function supportsAttribute($attribute) {
          return $attribute === 'rate_post';
      }
      
  4. Bootstrap CSS/JS Conflicts

    • Error: Styling breaks if Bootstrap is loaded twice.
    • Fix: Exclude default Bootstrap assets if already included:
      {% block stylesheets %}
          {{ parent() }}
          {% if not app.hasBootstrap %}
              {{ asset('bundles/ccdnforum/css/bootstrap.css') }}
          {% endif %}
      {% endblock %}
      

Debugging Tips

  • 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));
    }
    

Extension Points

  1. Custom Rating Logic Override the rating manager:

    # services.yml
    ccdn_forum.karma.manager:
        class: AppBundle\Service\CustomKarmaManager
        parent: ccdn_forum.karma.manager
    
  2. 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;
    }
    
  3. Localization Translate rating labels (e.g., "Upvote," "Downvote") by overriding Twig templates:

    {# templates/CCDNForumKarmaBundle/Karma/rate.html.twig #}
    {% trans %}Upvote{% endtrans %}
    
  4. 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
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor