PHP code example of tourze / doctrine-random-bundle

1. Go to this page and download the library: Download tourze/doctrine-random-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tourze / doctrine-random-bundle example snippets


use Tourze\DoctrineRandomBundle\Attribute\RandomStringColumn;

class YourEntity
{
    #[RandomStringColumn(prefix: 'user_', length: 20)]
    private string $randomId;

    public function getRandomId(): string
    {
        return $this->randomId;
    }

    public function setRandomId(string $randomId): self
    {
        $this->randomId = $randomId;
        return $this;
    }
}

$entity = new YourEntity();
$entityManager->persist($entity);
$entityManager->flush();
// $entity->getRandomId() will return something like 'user_a1b2c3d4e5f6g7h8i9'

use Tourze\DoctrineRandomBundle\Service\RandomService;

// Inject the service
public function __construct(
    private readonly RandomService $randomService,
    private readonly EntityManagerInterface $entityManager,
) {}

// Get random records
$queryBuilder = $this->entityManager->createQueryBuilder()
    ->select('u')
    ->from(User::class, 'u')
    ->where('u.active = :active')
    ->setParameter('active', true);

// Get 3 random users
$randomUsers = $this->randomService->getRandomResult($queryBuilder, 3);

foreach ($randomUsers as $user) {
    // Process each random user
}

class Product
{
    #[RandomStringColumn(prefix: 'SKU-', length: 12)]
    private string $sku;

    #[RandomStringColumn(length: 8)]
    private string $code;

    #[RandomStringColumn(prefix: 'REF_', length: 16)]
    private string $reference;
}

// Get random products with specific conditions
$queryBuilder = $this->entityManager->createQueryBuilder()
    ->select('p')
    ->from(Product::class, 'p')
    ->join('p.category', 'c')
    ->where('p.active = :active')
    ->andWhere('c.featured = :featured')
    ->andWhere('p.stock > :minStock')
    ->setParameter('active', true)
    ->setParameter('featured', true)
    ->setParameter('minStock', 0);

$randomProducts = $this->randomService->getRandomResult($queryBuilder, 5);