Installation
composer require amzs/random-bundle
For non-Flex projects, manually add Amzs\RandomBundle\AmzsRandomBundle::class to config/bundles.php.
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]);
}
}
Key Classes
RandomGenerator: Core service for generating random numbers.RandomStringGenerator: For alphanumeric strings (e.g., tokens, IDs).Generating Random Numbers
// Integer between 1-100
$this->random->getRandomInt(1, 100);
// Float with 2 decimal places
$this->random->getRandomFloat(0, 10, 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);
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
Integration with Forms/Validation
// Generate a random password in a registration form
$password = $this->randomString->generate(12);
$user->password = $password;
Dependency Injection
public function __construct(
private RandomGenerator $random,
private RandomStringGenerator $randomString
) {}
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']
Testing Use seeds for deterministic tests:
public function testRandomNumberGeneration()
{
$random = $this->get(RandomGenerator::class);
$random->setSeed(42);
$this->assertEquals(42, $random->getRandomInt(1, 100));
}
Configuration
Override defaults in config/packages/amzs_random.yaml:
amzs_random:
random_string:
length: 24 # Default length for generate()
chars: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
Thread Safety
mt_rand()/random_int() under the hood, which are not thread-safe in PHP’s CLI multi-process mode.pcntl_fork() carefully.Floating-Point Precision
getRandomFloat() may return unexpected results for very large ranges (e.g., 0 to 1e20).0 to 1000).Seeding Collisions
APP_RANDOM_SEED from .env).Doctrine ORM Dependency
doctrine/orm, even if you’re not using Doctrine.Symfony Version Compatibility
Random component).Unexpected Values
getRandomInt(10, 5) will throw an exception).var_dump() to inspect generated values:
var_dump($this->random->getRandomInt(1, 100)); // Debug output
Performance Bottlenecks
Service Not Found
config/bundles.php.php bin/console cache:clear
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
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));
}
}
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
}
}
Security
random_int() (via getRandomInt()) for cryptographic operations (e.g., tokens, passwords).mt_rand() for security-sensitive tasks (though the bundle defaults to random_int()).Localization
DateTime utilities:
$randomDays = $this->random->getRandomInt(1, 30);
$randomDate = new \DateTime()->modify("+$randomDays days");
Testing Edge Cases
getRandomInt(PHP_INT_MIN, PHP_INT_MAX)).pcntl_fork().Performance Testing
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
$this->random->getRandomInt(1, 100);
}
$time = microtime(true) - $start;
How can I help you explore Laravel packages today?