How rajeshmk/laravel-sequence works
1. What this repository is
- A Laravel package that generates concurrency-safe, human-readable sequence numbers.
- It is not an app; it is a reusable library centered on one persistence-backed counter service.
2. Primary runtime boundary
- The package is built around a hard requirement: sequence generation must happen inside a database transaction.
- Correctness depends on row-level locking (SELECT ... FOR UPDATE) against a sequences table, so the key architectural boundary is “caller-owned transaction + package-managed counter row.”
3. Core sequence flow
- Consumers call the sequence('name') helper.
- That returns a fluent NextSequence builder, which collects options like prefix, padding, range, grouping, and formatting.
- When next() is called, the builder resolves the active connection, locks the matching counter row, increments last_number, formats the result, and returns the final string.
4. Persistence model
- The state lives in a sequences table created by the package migration.
- Each counter is keyed by a (name, group_by) tuple, with last_number holding the current numeric position.
- This means grouping is not just display logic; it determines which counter row is used and when numbering resets.
5. Configuration subsystem
- config/sequence.php controls package-wide behavior such as table name, database connection, model class, and strict validation mode.
- SequenceConfig is the internal configuration object used by both the fluent API and Eloquent trait integration.
- It also owns policy choices like min/max ranges, overflow behavior, pad length, prefix, and format template/callback handling.
6. Eloquent model integration
- The HasSequence trait lets application models auto-assign sequence values during the creating lifecycle event.
- A model defines sequenceColumns(), returning a SequenceColumnCollection that maps model columns to per-column SequenceConfig.
- This path still depends on a transaction; the trait does not replace the concurrency model, it just automates when the sequence is reserved.
7. Grouping and scope rules
- The package supports grouping by raw values, date-based helpers, or persisted Eloquent models.
- Helpers like groupByYear(), groupByMonth(), groupByDay(), and belongsTo() affect the storage key, not the rendered output.
- If the group token should also appear in the final number, the caller must include it in the prefix or format string.
8. Formatting and number policy
- prefix(), padLength(), and format() shape the returned string only after the numeric counter is reserved.
- Range controls (range(), bounded(), cyclingRange(), cycle(), throwOnOverflow()) govern numeric limits and overflow behavior.
- Overflow is explicit and typed, with failure or cycling behavior chosen by configuration.
9. Error and event boundaries
- The library has a dedicated exception hierarchy for invalid config, invalid models, missing transactions, validation failures, and overflow.
- It also emits a SequenceAssigned event whenever a value is reserved, carrying the internal name, raw number, final sequence string, and group key.
- That makes reservation observable without coupling business code to the persistence implementation.
10. Package wiring
- SequenceServiceProvider is the integration point for Laravel: it boots the package, loads migrations, and enables helper availability.
- helper-functions/sequence-helpers.php provides the global entry helper used by consumers.
- The package is designed as a thin Laravel-facing facade over the internal sequence engine.
11. Support and domain classes
- Support/NextSequence, Support/SequenceConfig, and Support/SequenceColumnCollection form the main fluent API and configuration model.
- Models/Sequence represents the persisted counter record.
- Enums/OverflowStrategy captures the overflow policy in a typed form rather than as loose flags.
12. Testing and regression strategy
- The unit tests focus on the builder, config validation, exceptions, and event construction.
- The scripts/ directory adds regression checks, including a concurrency script that simulates parallel workers to verify that locking prevents duplicates.
- That test layout mirrors the architecture: most logic is pure/configurable, while correctness under load is verified with process-level concurrency tests.
Main entry points: SequenceConfig.php SequenceConfig · NextSequence.php NextSequence · SequenceException.php SequenceException · HasSequence.php HasSequence trait
Components 18
Laravel integration
Framework entry points and consumer-facing helpers.
- Service Provider · Registers package services, migrations, and helper availability.
src/SequenceServiceProvider.php - sequence() helper · Entry helper that creates the fluent sequence builder.
helper-functions/sequence-helpers.php
Sequence engine
Builder, config, and policy that drive sequence reservation.
- NextSequence · Collects prefix, padding, grouping, range, and format options before reserving a number.
src/Support/NextSequence.php - SequenceConfig · Holds configuration and validation rules for sequence generation.
src/Support/SequenceConfig.php - Column map · Maps model columns to per-column sequence configuration.
src/Support/SequenceColumnCollection.php - Reserve flow · Caller-owned transaction plus locked row increment and formatting.
Persistence layer
Database-backed counter storage and schema.
- Sequence model · Persists the counter row keyed by name and group.
src/Models/Sequence.php - Create sequences · Creates the sequences table used for counter storage.
database/migrations/2023_01_01_100000_create_sequences.php
Domain support
Typed values, events, and exceptions.
- OverflowStrategy · Typed overflow policy for bounded and cycling ranges.
src/Enums/OverflowStrategy.php - SequenceAssigned · Emitted when a sequence value is reserved.
src/Events/SequenceAssigned.php - SequenceException · Shared exception root for package failures.
src/Exceptions/SequenceException.php - Config errors · Invalid configuration and model setup failures.
src/Exceptions/SequenceConfigException.php - Txn errors · Raised when sequence generation is attempted without the required transaction.
src/Exceptions/SequenceTransactionException.php - Validation errors · Raised for invalid values and policy violations.
src/Exceptions/SequenceValidationException.php - Overflow errors · Raised when numeric bounds are exceeded without cycling.
src/Exceptions/SequenceOverflowException.php
Model automation
Eloquent trait path for auto-assigning sequences.
- HasSequence trait · Auto-assigns sequence values during model creation.
src/Traits/HasSequence.php
Verification
Unit and regression coverage for correctness and concurrency.
- Regression scripts · Process-level scripts that exercise locking and first-number behavior.
scripts/regression_concurrency.php - Unit tests · Covers builder behavior, config validation, exceptions, and event construction.
tests/Unit/NextSequenceTest.php
Connections 25
- Service Provider → sequence() helper: loads · Exposes the helper and boots package wiring.
- Service Provider → Create sequences: publishes · Registers the migration for the sequences table.
- sequence() helper → NextSequence: creates · Returns a fluent builder for a named sequence.
- NextSequence → SequenceConfig: uses · Applies policy, validation, and formatting options.
- HasSequence trait → Column map: maps · Collects per-column sequence definitions from the model.
- Column map → SequenceConfig: contains · Stores configuration objects for each sequence column.
- HasSequence trait → NextSequence: delegates · Uses the fluent builder to reserve values during model creation.
- NextSequence → Reserve flow: drives · The builder triggers the reservation and formatting path.
- Reserve flow → Sequence model: locks · Reads and increments the matching counter row with row-level locking.
- Reserve flow → SequenceAssigned: emits · Publishes the assigned value after reservation.
- Reserve flow → Txn errors: requires · Depends on an active database transaction for correctness.
- Reserve flow → OverflowStrategy: applies · Uses typed overflow policy to decide failure or cycling behavior.
- Sequence model → Create sequences: persists in · The model is backed by the package-created sequences table.
- SequenceConfig → OverflowStrategy: configures · Encodes bounded and cycling range behavior.
- SequenceConfig → Config errors: validates · Rejects invalid package and sequence configuration.
- SequenceConfig → Validation errors: validates · Enforces input and formatting constraints.
- SequenceException → Config errors: specializes · Configuration failures derive from the shared exception root.
- SequenceException → Txn errors: specializes · Transaction failures derive from the shared exception root.
- SequenceException → Validation errors: specializes · Validation failures derive from the shared exception root.
- SequenceException → Overflow errors: specializes · Overflow failures derive from the shared exception root.
- HasSequence trait → Txn errors: depends on · Still requires the caller to wrap model creation in a transaction.
- Unit tests → NextSequence: covers · Exercises fluent sequence construction and formatting behavior.
- Unit tests → SequenceConfig: covers · Verifies configuration and validation rules.
- Unit tests → SequenceAssigned: covers · Checks event payload construction.
- Regression scripts → Reserve flow: verifies · Confirms locking and concurrency-safe numbering under load.