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

Badge Bundle Laravel Package

antwebes/badge-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require antwebes/badge-bundle

Register the bundle in config/bundles.php:

return [
    // ...
    Antwebes\BadgeBundle\AntwebesBadgeBundle::class => ['all' => true],
];
  1. Database Configuration:

    • The bundle is storage-agnostic but includes an ORM (Doctrine) implementation by default.
    • Run migrations (if using Doctrine):
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      
  2. First Use Case:

    • Define a Badge: Create a badge entity (e.g., UserBadge) extending Antwebes\BadgeBundle\Model\BadgeInterface:
      use Antwebes\BadgeBundle\Model\BadgeInterface;
      
      class UserBadge implements BadgeInterface
      {
          private $id;
          private $name;
          private $description;
          private $icon;
      
          // Implement BadgeInterface methods (getters/setters)
      }
      
    • Register the Badge: Configure the badge in config/packages/antwebes_badge.yaml:
      antwebes_badge:
          badges:
              user_badge:
                  class: App\Entity\UserBadge
                  requirements:
                      - { property: 'posts', operator: '>', value: 10 }
                      - { property: 'comments', operator: '>', value: 5 }
      
  3. Check Badges for a User:

    use Antwebes\BadgeBundle\Manager\BadgeManagerInterface;
    
    $badgeManager = $this->container->get('antwebes_badge.manager');
    $badges = $badgeManager->getBadgesForUser($user);
    

Implementation Patterns

Core Workflows

  1. Badge Assignment Logic:

    • Trigger Badges on Events: Use Symfony events (e.g., kernel.request) to check and assign badges dynamically:
      use Symfony\Component\HttpKernel\Event\RequestEvent;
      use Antwebes\BadgeBundle\Event\BadgeCheckEvent;
      
      $badgeManager->checkAndAssignBadges($user);
      
    • Batch Processing: For large user bases, use a command to process badges asynchronously:
      use Symfony\Component\Console\Command\Command;
      use Symfony\Component\Console\Input\InputInterface;
      use Symfony\Component\Console\Output\OutputInterface;
      
      class ProcessBadgesCommand extends Command
      {
          protected function execute(InputInterface $input, OutputInterface $output)
          {
              $badgeManager = $this->getContainer()->get('antwebes_badge.manager');
              $badgeManager->processAllUsers();
          }
      }
      
  2. Custom Requirements:

    • Extend the BadgeRequirement class to add custom logic:
      use Antwebes\BadgeBundle\Model\BadgeRequirementInterface;
      
      class CustomRequirement implements BadgeRequirementInterface
      {
          public function isSatisfied($user, $badge)
          {
              // Custom logic (e.g., API call, external service)
              return $this->externalService->validate($user);
          }
      }
      
    • Register in antwebes_badge.yaml:
      antwebes_badge:
          badges:
              custom_badge:
                  requirements:
                      - { class: App\Badge\CustomRequirement }
      
  3. Displaying Badges:

    • Twig Integration: Pass badges to templates:
      {% for badge in badges %}
          <div class="badge">
              <img src="{{ asset(badge.icon) }}" alt="{{ badge.name }}">
              <span>{{ badge.name }}</span>
          </div>
      {% endfor %}
      
    • User Profile Badges: Extend the User entity to store awarded badges:
      class User extends BaseUser
      {
          /** @ORM\ManyToMany(targetEntity="App\Entity\UserBadge") */
          private $badges;
      }
      
  4. Badge Tiers:

    • Implement progressive badges (e.g., Bronze/Silver/Gold) by chaining requirements:
      antwebes_badge:
          badges:
              bronze:
                  requirements: [{ property: 'posts', operator: '>', value: 10 }]
              silver:
                  requirements:
                      - { property: 'posts', operator: '>', value: 50 }
                      - { property: 'comments', operator: '>', value: 20 }
              gold:
                  requirements:
                      - { property: 'posts', operator: '>', value: 100 }
                      - { property: 'comments', operator: '>', value: 50 }
      

Gotchas and Tips

Common Pitfalls

  1. Doctrine ORM Assumptions:

    • The bundle assumes Doctrine ORM by default. If using another storage (e.g., Propel), override the BadgeManager and BadgeRepository services.
    • Fix: Configure custom services in config/services.yaml:
      services:
          antwebes_badge.manager:
              class: App\Badge\CustomBadgeManager
              arguments: ['@antwebes_badge.repository.custom']
      
  2. Requirement Property Access:

    • Requirements use property keys to access user attributes. If the property is private or uses getters/setters, the bundle may fail silently.
    • Fix: Use fully qualified getter methods (e.g., getPosts() instead of posts):
      requirements:
          - { property: 'getPosts', operator: '>', value: 10 }
      
  3. Event Dispatching:

    • Badges are not automatically checked on every request. Manually trigger checks where needed (e.g., after user actions).
    • Tip: Use a listener for critical events (e.g., user.post_create):
      use Antwebes\BadgeBundle\Event\BadgeCheckEvent;
      
      public function onPostCreate(PostEvent $event)
      {
          $badgeManager->checkAndAssignBadges($event->getUser());
      }
      
  4. Performance:

    • Checking badges for every user on every request is expensive. Cache results or use a queue system (e.g., Symfony Messenger).
    • Tip: Cache awarded badges per user:
      $badgeManager->getBadgesForUser($user, true); // Cache results
      

Debugging Tips

  1. Enable Debug Mode:

    • The bundle logs badge checks in dev environment. Enable debug mode in config/packages/dev/antwebes_badge.yaml:
      antwebes_badge:
          debug: true
      
  2. Check Requirement Validation:

    • Log requirement failures to identify why a badge isn’t awarded:
      $badgeManager->checkAndAssignBadges($user, true); // Verbose mode
      
  3. Database Schema:

    • If migrations fail, manually check the badge and user_badge tables. The bundle expects:
      • badge table with id, name, description, icon.
      • user_badge junction table for awarded badges.

Extension Points

  1. Custom Storage:

    • Implement Antwebes\BadgeBundle\Repository\BadgeRepositoryInterface for non-Doctrine backends (e.g., MongoDB, Redis).
    • Example:
      class RedisBadgeRepository implements BadgeRepositoryInterface
      {
          public function findByUser(UserInterface $user)
          {
              return $this->redis->hGetAll('badge:' . $user->getId());
          }
      }
      
  2. Badge Events:

    • Extend the bundle’s event system to trigger actions when badges are awarded/revoked:
      use Antwebes\BadgeBundle\Event\BadgeEvent;
      
      $dispatcher->dispatch(new BadgeEvent($user, $badge, BadgeEvent::BADGE_AWARDED));
      
  3. Badge UI Components:

    • Create reusable Twig components for badges:
      {# templates/components/badge.html.twig #}
      <div class="badge {{ badge.type }}">
          <i class="{{ badge.icon }}"></i>
          <span>{{ badge.name }}</span>
      </div>
      
    • Include in layouts:
      {% include 'components/badge.html.twig' with { badge: badge } %}
      
  4. Badge Analytics:

    • Track badge award rates or user engagement:
      $badgeManager->getBadgeStats('user_badge'); // Hypothetical method
      
    • Tip: Log badge events to a monitoring system (e.g., Datadog, Sentry):
      $this->logger->info('Badge awarded', [
          'user_id' => $user->getId(),
          'badge' => $badge->getName(),
      ]);
      
  5. Localization:

    • Translate badge names/descriptions using Symfony’s translation system:
      # config/packages/antwebes_badge.yaml
      antwebes
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui