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

Lottery Laravel Package

lonban/lottery

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require lonban/lottery
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Lonban\Lottery\LotteryServiceProvider"
    
  2. First Use Case: Define a prize pool in config/lottery.php:

    'prize_pools' => [
        'wheel' => [
            'type' => 'wheel', // or 'list', 'random'
            'items' => [
                ['name' => 'First Prize', 'weight' => 10],
                ['name' => 'Second Prize', 'weight' => 5],
                ['name' => 'Consolation', 'weight' => 85],
            ],
        ],
    ],
    
  3. Trigger a Draw:

    use Lonban\Lottery\Facades\Lottery;
    
    $winner = Lottery::draw('wheel');
    // Returns: ['name' => 'First Prize', 'weight' => 10]
    

Implementation Patterns

Core Workflows

  1. Prize Pool Management:

    • Static Config: Define pools in config/lottery.php for simple use cases.
    • Dynamic Pools: Extend via service providers or use Lottery::addPool():
      Lottery::addPool('dynamic_wheel', [
          'type' => 'wheel',
          'items' => [...],
      ]);
      
  2. Weighted Randomness:

    • Use weight keys to skew probabilities (e.g., weight: 10 = 10x chance of weight: 1).
    • Validate weights sum to 100% for wheel/list types.
  3. Integration with Events:

    • Hook into LotteryDrawn events (if extended) or log draws manually:
      event(new \App\Events\PrizeDrawn($winner));
      
  4. User-Specific Draws:

    • Store user IDs in a user_id field and filter draws later:
      Lottery::draw('wheel', ['user_id' => auth()->id()]);
      

Advanced Patterns

  • Custom Draw Logic: Extend Lonban\Lottery\Contracts\DrawStrategy for non-standard distributions (e.g., time-based weights).
  • Database Backing: Store pools in a prize_pools table and hydrate via Eloquent:
    Lottery::addPool('db_wheel', PrizePool::find(1)->toArray());
    

Gotchas and Tips

Pitfalls

  1. Weight Validation:

    • wheel/list types require weights to sum to 100. Use Lottery::validatePool() to check:
      Lottery::validatePool('wheel'); // Throws \InvalidArgumentException if invalid.
      
    • Fix: Normalize weights in config or runtime:
      $weights = array_map(fn($item) => $item['weight'] / array_sum(array_column($items, 'weight')) * 100, $items);
      
  2. Random Seed Collisions:

    • Default random type uses mt_rand(). For reproducibility, set a seed:
      mt_srand(123); // Before drawing.
      
  3. Missing Config:

    • If prize_pools is empty, Lottery::draw() throws RuntimeException. Validate early:
      if (empty(config('lottery.prize_pools'))) {
          throw new \RuntimeException('No prize pools configured.');
      }
      

Debugging Tips

  • Log Draws: Wrap draws in a try-catch to log failures:
    try {
        $winner = Lottery::draw('wheel');
    } catch (\Exception $e) {
        \Log::error("Lottery draw failed: {$e->getMessage()}");
    }
    
  • Test Weights: Run a loop to verify distributions:
    $results = collect([]);
    for ($i = 0; $i < 1000; $i++) {
        $results->push(Lottery::draw('wheel')['name']);
    }
    // Check if results match expected weights.
    

Extension Points

  1. Custom Draw Types: Implement DrawStrategy for new types (e.g., time_based):

    class TimeBasedStrategy implements DrawStrategy {
        public function draw(array $items) {
            // Custom logic (e.g., higher chance at night).
        }
    }
    

    Register via service provider:

    Lottery::extend('time_based', function () {
        return new TimeBasedStrategy();
    });
    
  2. Middleware for Draws: Add user validation or rate-limiting:

    Lottery::macro('drawWithMiddleware', function ($pool, $context = []) {
        if (!auth()->check()) {
            throw new \UnauthorizedHttpException;
        }
        return $this->draw($pool, $context);
    });
    
  3. Localization: Override prize names dynamically:

    Lottery::macro('drawLocalized', function ($pool) {
        $winner = $this->draw($pool);
        $winner['name'] = __("lottery.{$winner['name']}");
        return $winner;
    });
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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