Weave Code
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

Data Generation Bundle Laravel Package

doctrine-fixtures/data-generation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require --dev doctrine-fixtures/data-generation-bundle
    

    Ensure it’s only installed in dev dependencies (as it’s for testing/data generation).

  2. Configure fixtures-config.yml Place the file in your project root (or config/ if preferred). Example:

    user:
      namespace: App\Entity\User
      defined_roles: [ROLE_USER, ROLE_ADMIN]
      rows: 10
    post:
      namespace: App\Entity\Post
      rows: 20
    
  3. Generate Data via CLI Run the generator with:

    php bin/console data:generate
    

    This populates your database with random test data based on the config.

  4. First Use Case: Quick Test Data Use this to seed a local database for:

    • Testing features (e.g., "Does pagination work with 100 users?").
    • Mocking APIs or services that require realistic data.
    • Demonstrating functionality to stakeholders.

Implementation Patterns

Workflow: Data-Driven Development

  1. Define Fixtures in fixtures-config.yml

    • Basic Entities: Specify namespace and rows for simple entities.
      product:
        namespace: App\Entity\Product
        rows: 50
      
    • Complex Entities: Use construct for entities requiring constructor args (e.g., relationships).
      order:
        namespace: App\Entity\Order
        construct: true  # Expects a User entity as first argument
        rows: 100
      
    • Custom Fields: Leverage Doctrine Fixtures’ addReference() for relationships. Example: Generate Order entities linked to pre-generated User entities.
  2. Dynamic Data Generation

    • Faker Integration: The bundle uses Faker under the hood. Customize data formats in your config:
      user:
        fields:
          email: "{{email}}"
          first_name: "{{firstName}}"
          last_name: "{{lastName}}"
      
    • Custom Rules: Extend the bundle’s DataGenerator class to add domain-specific logic (e.g., valid email domains, date ranges).
  3. Seeding Workflows

    • One-Time Setup: Run data:generate during php artisan migrate:fresh --seed.
    • Incremental Updates: Use --force to regenerate data without dropping tables:
      php bin/console data:generate --force
      
    • Conditional Generation: Skip entities with rows: 0 or use environment variables to toggle features.
  4. Integration with Tests

    • PHPUnit Setup: Combine with DatabaseTransactions or DatabaseMigrations traits:
      use DoctrineFixturesBundle\Test\FixturesTrait;
      use DoctrineFixturesBundle\Test\IsolatedDatabaseTestCase;
      
      class UserTest extends IsolatedDatabaseTestCase
      {
          use FixturesTrait;
      
          protected function getFixturesDir(): string
          {
              return __DIR__ . '/../fixtures';
          }
      
          public function testSomething()
          {
              $this->loadFixtures([UserFixture::class]);
              // Test logic here
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Constructor Dependencies

    • If construct: true is set but no referenced entity exists, generation fails.
    • Fix: Ensure dependent entities are defined before the entity requiring them in fixtures-config.yml.
  2. Unique Constraints

    • Faker-generated data (e.g., emails) may violate uniqueness.
    • Fix: Use unique: true in config or override the generator to append UUIDs:
      user:
        fields:
          email: "{{email}}@{{domain}}.com-{{uuid}}"
      
  3. Database Truncation

    • By default, data:generate truncates tables. Use --force carefully in production-like environments.
    • Tip: Add a --dry-run flag to preview SQL (contribute upstream if needed).
  4. Performance

    • Generating 10K+ rows may time out. Batch operations or async processing (e.g., queues) can help.
    • Tip: Use rows: 1000 for initial tests, then scale up.

Debugging

  1. Verbose Output Enable debug mode to see generated data:

    php bin/console data:generate -vvv
    
  2. Custom Generators Override the default generator for an entity:

    custom_user:
      namespace: App\Entity\User
      generator: App\DataFixtures\CustomUserGenerator
    

    Implement DataGeneratorInterface in your class.

  3. Environment-Specific Configs Use Symfony’s %env% or parameters.yml to switch fixtures between dev/test:

    # config/packages/dev/fixtures-config.yml
    user:
      rows: 1000  # More data for dev
    

Extension Points

  1. Add Custom Data Providers Extend the bundle’s DataGenerator to support new field types (e.g., slug from title):

    // src/DataFixtures/CustomGenerator.php
    use DoctrineFixturesBundle\DataGenerator\DataGeneratorInterface;
    
    class CustomGenerator implements DataGeneratorInterface
    {
        public function generate(array $data, EntityManagerInterface $em): void
        {
            $data['slug'] = Str::slug($data['title']);
            // ...
        }
    }
    
  2. Post-Generation Hooks Use Symfony’s event system to run logic after generation:

    // config/services.yaml
    App\EventListener\PostDataGenerationListener:
        tags:
            - { name: kernel.event_listener, event: data.generation.post, method: onPostGenerate }
    
  3. Localization The bundle supports Faker’s locales. Specify in config:

    user:
      locale: fr_FR  # French names/addresses
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle