Weave 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

Random Bundle Laravel Package

amzs/random-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require amzs/random-bundle
    

    For non-Flex projects, manually add Amzs\RandomBundle\AmzsRandomBundle::class to config/bundles.php.

  2. First Use Case Inject the RandomGenerator service into a controller or service:

    use Amzs\RandomBundle\Service\RandomGenerator;
    
    class MyController extends AbstractController
    {
        public function __construct(private RandomGenerator $random)
        {
        }
    
        public function generateRandomNumber()
        {
            $randomInt = $this->random->getRandomInt(1, 100); // Returns int between 1-100
            $randomFloat = $this->random->getRandomFloat(0, 10, 2); // Returns float (e.g., 3.14)
            return $this->json(['int' => $randomInt, 'float' => $randomFloat]);
        }
    }
    
  3. Key Classes

    • RandomGenerator: Core service for generating random numbers.
    • RandomStringGenerator: For alphanumeric strings (e.g., tokens, IDs).

Implementation Patterns

Common Workflows

  1. Generating Random Numbers

    // Integer between 1-100
    $this->random->getRandomInt(1, 100);
    
    // Float with 2 decimal places
    $this->random->getRandomFloat(0, 10, 2);
    
  2. Random Strings (e.g., Tokens, UUIDs)

    // Alphanumeric string (default: 32 chars)
    $token = $this->randomString->generate();
    
    // Custom length (e.g., 16 chars)
    $shortToken = $this->randomString->generate(16);
    
    // Numeric-only string
    $numericString = $this->randomString->generateNumeric(8);
    
  3. Seeding for Reproducibility

    // Set a seed (e.g., for testing)
    $this->random->setSeed(12345);
    $reproducibleValue = $this->random->getRandomInt(1, 100); // Always returns the same value
    
  4. Integration with Forms/Validation

    // Generate a random password in a registration form
    $password = $this->randomString->generate(12);
    $user->password = $password;
    
  5. Dependency Injection

    • Prefer constructor injection for services:
      public function __construct(
          private RandomGenerator $random,
          private RandomStringGenerator $randomString
      ) {}
      
    • Use autowiring (enabled by default in Symfony 4.3+).

Advanced Patterns

  1. Custom Random Logic Extend the bundle’s services or create decorators:

    // src/Service/DecoratedRandomGenerator.php
    class DecoratedRandomGenerator implements RandomGeneratorInterface
    {
        public function __construct(private RandomGenerator $decorated)
        {}
    
        public function getRandomInt(int $min, int $max): int
        {
            $value = $this->decorated->getRandomInt($min, $max);
            return $value * 2; // Example: Double the value
        }
    }
    

    Register the decorator in services.yaml:

    services:
        App\Service\DecoratedRandomGenerator:
            decorates: 'amzs_random.random_generator'
            arguments: ['@amzs_random.random_generator.decorated']
    
  2. Testing Use seeds for deterministic tests:

    public function testRandomNumberGeneration()
    {
        $random = $this->get(RandomGenerator::class);
        $random->setSeed(42);
        $this->assertEquals(42, $random->getRandomInt(1, 100));
    }
    
  3. Configuration Override defaults in config/packages/amzs_random.yaml:

    amzs_random:
        random_string:
            length: 24  # Default length for generate()
            chars: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    

Gotchas and Tips

Pitfalls

  1. Thread Safety

    • The bundle uses PHP’s mt_rand()/random_int() under the hood, which are not thread-safe in PHP’s CLI multi-process mode.
    • Workaround: Avoid parallel execution of random operations in CLI scripts. Use pcntl_fork() carefully.
  2. Floating-Point Precision

    • getRandomFloat() may return unexpected results for very large ranges (e.g., 0 to 1e20).
    • Tip: Limit ranges to avoid precision loss (e.g., 0 to 1000).
  3. Seeding Collisions

    • Reusing the same seed across tests or environments can lead to predictable "random" values.
    • Tip: Use environment-specific seeds (e.g., APP_RANDOM_SEED from .env).
  4. Doctrine ORM Dependency

    • The bundle requires doctrine/orm, even if you’re not using Doctrine.
    • Note: This is a hard dependency; remove it if you’re not using ORM.
  5. Symfony Version Compatibility

    • The bundle supports Symfony 5.4–7.0 but may lack features for newer versions (e.g., Symfony 8’s Random component).
    • Tip: Check for updates or fork the package if you need newer Symfony support.

Debugging

  1. Unexpected Values

    • Verify min/max ranges (e.g., getRandomInt(10, 5) will throw an exception).
    • Use var_dump() to inspect generated values:
      var_dump($this->random->getRandomInt(1, 100)); // Debug output
      
  2. Performance Bottlenecks

    • Heavy random operations in loops can slow down CLI commands.
    • Optimization: Cache random values if they don’t need to change frequently.
  3. Service Not Found

    • Ensure the bundle is enabled in config/bundles.php.
    • Clear cache after installation:
      php bin/console cache:clear
      

Extension Points

  1. Custom Random Sources Implement Amzs\RandomBundle\Service\RandomGeneratorInterface to replace the default generator:

    class CustomRandomGenerator implements RandomGeneratorInterface
    {
        public function getRandomInt(int $min, int $max): int
        {
            return random_int($min, $max); // Use PHP’s built-in
        }
    }
    

    Register it as a service:

    services:
        amzs_random.random_generator:
            class: App\Service\CustomRandomGenerator
    
  2. Adding New Methods Extend RandomGenerator or RandomStringGenerator and override methods:

    class ExtendedRandomGenerator extends RandomGenerator
    {
        public function getRandomHex(int $length = 8): string
        {
            return bin2hex(random_bytes($length / 2));
        }
    }
    
  3. Event Listeners The bundle doesn’t expose events, but you can wrap its methods in listeners for logging/auditing:

    // src/EventListener/RandomListener.php
    class RandomListener
    {
        public function __invoke(RandomGeneratedEvent $event)
        {
            // Log or process the generated value
        }
    }
    

Pro Tips

  1. Security

    • Use random_int() (via getRandomInt()) for cryptographic operations (e.g., tokens, passwords).
    • Avoid mt_rand() for security-sensitive tasks (though the bundle defaults to random_int()).
  2. Localization

    • For locale-aware randomness (e.g., random dates), combine with Symfony’s DateTime utilities:
      $randomDays = $this->random->getRandomInt(1, 30);
      $randomDate = new \DateTime()->modify("+$randomDays days");
      
  3. Testing Edge Cases

    • Test with extreme values (e.g., getRandomInt(PHP_INT_MIN, PHP_INT_MAX)).
    • Verify thread safety in CLI scripts with pcntl_fork().
  4. Performance Testing

    • Benchmark random operations in loops:
      $start = microtime(true);
      for ($i = 0; $i < 10000; $i++) {
          $this->random->getRandomInt(1, 100);
      }
      $time = microtime(true) - $start;
      
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.
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin