PHPackages                             tourze/doctrine-random-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. tourze/doctrine-random-bundle

ActiveLibrary[Database &amp; ORM](/categories/database)

tourze/doctrine-random-bundle
=============================

Doctrine随机增强

1.0.0(6mo ago)02.1k4MITPHPCI passing

Since Mar 24Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/doctrine-random-bundle)[ Packagist](https://packagist.org/packages/tourze/doctrine-random-bundle)[ RSS](/packages/tourze-doctrine-random-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (24)Versions (10)Used By (4)

Doctrine Random Bundle
======================

[](#doctrine-random-bundle)

[![Latest Version](https://camo.githubusercontent.com/73acc8e847906461c4e295398c8c542ea14466bc5888b660d043fa0dda51346e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f646f637472696e652d72616e646f6d2d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/doctrine-random-bundle)[![Total Downloads](https://camo.githubusercontent.com/546742118ac8960a3c4eb7caefd10a98b2d396f442a0402aca2965b78b5e0e22/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f75727a652f646f637472696e652d72616e646f6d2d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/doctrine-random-bundle)[![PHP Version](https://camo.githubusercontent.com/1a0d5390404c568c7f9530d73b15e0ea02ce746c8019b820a903999e3d25b433/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f646f637472696e652d72616e646f6d2d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/doctrine-random-bundle)[![License](https://camo.githubusercontent.com/14513c575caebe7efbe197b345a08be40b16468e42ddb865edc3db6e6f363dfc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f646f637472696e652d72616e646f6d2d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/doctrine-random-bundle)[![Code Coverage](https://camo.githubusercontent.com/71bd2b6cb660d5160d4a7ffc132cdd70141763068fa2ff4fe766d8661bcfa64e/68747470733a2f2f636f6465636f762e696f2f67682f746f75727a652f646f637472696e652d72616e646f6d2d62756e646c652f6272616e63682f6d61696e2f67726170682f62616467652e737667)](https://codecov.io/gh/tourze/doctrine-random-bundle)

[English](README.md) | [中文](README.zh-CN.md)

A Symfony bundle that provides automatic random string generation for Doctrine entity properties and random database query functionality with PHP attributes.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [RandomService Usage](#randomservice-usage)
- [Advanced Usage](#advanced-usage)
- [Advanced Details](#advanced-details)
- [Security](#security)
- [Contribution Guide](#contribution-guide)
- [License](#license)
- [Changelog](#changelog)
- [Author](#author)

---

Features
--------

[](#features)

- **Random String Generation**: Generate random string values for entity properties using PHP attributes
- **Random Database Queries**: Service to fetch random records from database with caching and locking support
- **Configurable**: Customizable prefix and string length for random strings
- **Automatic Generation**: Triggers on entity creation (Doctrine prePersist event)
- **Non-Destructive**: Skips generation if property already has a value
- **Performance Optimized**: Uses caching and distributed locking to prevent conflicts
- **Symfony Integration**: Simple integration with Symfony auto-configuration

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Symfony 6.4 or higher
- Doctrine Bundle 2.13 or higher
- Doctrine ORM 2.20/3.0 or higher

Installation
------------

[](#installation)

```
composer require tourze/doctrine-random-bundle
```

This bundle is auto-registered by Symfony Flex. No extra configuration is required.

Quick Start
-----------

[](#quick-start)

Add the `RandomStringColumn` attribute to your entity property:

```
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;
    }
}
```

When you persist a new entity, the `randomId` property will be automatically filled if it is empty:

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

---

Configuration
-------------

[](#configuration)

The `RandomStringColumn` attribute accepts the following parameters:

- `prefix`: String prefix for the random value (default: '')
- `length`: Length of the random string (default: 16)

---

RandomService Usage
-------------------

[](#randomservice-usage)

The bundle also provides a `RandomService` for fetching random records from the database with caching and locking support:

```
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
}
```

### RandomService Features

[](#randomservice-features)

- **Distributed Locking**: Prevents multiple processes from getting the same random record
- **Caching**: Caches ID lists for better performance (1-minute TTL)
- **Flexible Querying**: Works with any QueryBuilder with WHERE conditions
- **Configurable Range**: Limits the cached ID range to optimize memory usage

---

Advanced Usage
--------------

[](#advanced-usage)

### Custom Random String Generation

[](#custom-random-string-generation)

You can use multiple `RandomStringColumn` attributes on different properties:

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

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

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

### Advanced RandomService Usage

[](#advanced-randomservice-usage)

The `RandomService` supports complex queries and offers fine-grained control:

```
// 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);
```

---

Advanced Details
----------------

[](#advanced-details)

- The bundle uses a Doctrine event listener (`RandomStringListener`) to automatically generate random strings for properties marked with the `RandomStringColumn` attribute during the `prePersist` event.
- If the property already has a value, it will not be overwritten.
- The random string is composed of numbers and upper/lowercase letters.
- The `RandomService` uses Symfony's Lock component and Cache component for performance optimization.

---

Security
--------

[](#security)

- Random strings are generated using PHP's `random_int()` function for cryptographic security
- The bundle respects existing property values and never overwrites them
- Distributed locking prevents race conditions in concurrent environments

---

Contribution Guide
------------------

[](#contribution-guide)

Contributions are welcome! To contribute:

- Open an issue for bug reports or feature requests.
- Submit a pull request with clear description and relevant tests.
- Follow PSR coding standards.
- Run tests with PHPUnit before submitting.

---

License
-------

[](#license)

This bundle is released under the MIT License. See the [LICENSE](LICENSE) file for details.

---

Changelog
---------

[](#changelog)

- v0.1.0: Initial release with random string attribute and random query service support.

---

Author
------

[](#author)

Maintained by [tourze](https://github.com/tourze).

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance71

Regular maintenance activity

Popularity15

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~27 days

Recently: every ~41 days

Total

9

Last Release

190d ago

Major Versions

0.1.4 → 1.0.02025-10-31

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

---

Tags

doctrinesymfony

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-doctrine-random-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-doctrine-random-bundle/health.svg)](https://phpackages.com/packages/tourze-doctrine-random-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M650](/packages/sylius-sylius)[contao/core-bundle

Contao Open Source CMS

1231.6M2.3k](/packages/contao-core-bundle)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
