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

Fixtures Bundle Laravel Package

atournayre/fixtures-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require atournayre/fixtures-bundle --dev
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Hautelook\AliceBundle\HautelookAliceBundle::class => ['dev' => true, 'test' => true],
        Atournayre\Bundle\FixtureBundle\AtournayreFixtureBundle::class => ['dev' => true, 'test' => true],
    ];
    
  2. First Fixture File: Create a YAML file (e.g., config/fixtures/users.yaml) with Alice syntax:

    App\Entity\User:
      user1:
        email: 'user1@example.com'
        password: '<hashPassword("password123")>'
        roles: ['ROLE_USER']
    
  3. Run Fixtures:

    php bin/console fixtures
    

First Use Case

Use this bundle to seed your database with test data for development, testing, or demos. Ideal for:

  • Populating a clean database with consistent test data.
  • Generating related entities (e.g., users with associated posts).
  • Overriding default AliceBundle behavior with custom providers (e.g., UUIDs, hashed passwords).

Implementation Patterns

Fixture File Structure

Organize fixtures by entity or feature:

config/fixtures/
├── users.yaml          # User entities
├── posts.yaml          # Post entities (with user references)
└── categories.yaml     # Category entities

Example: Related Entities

App\Entity\Post:
  post1:
    title: 'First Post'
    content: 'Lorem ipsum...'
    author: '<entity<user1, App\Entity\User>>'  # Reference by fixture ID
    category: '<entity<category1, App\Entity\Category>>'

Dynamic Data Providers

Leverage built-in providers for dynamic values:

  • UUIDs: <uuidV4()>, <uuidV8(uuid)>
  • Dates: <currentDateWithTime(10:30)>, <randomHourWithDate()>
  • Passwords: <hashPassword("plaintext")>

Example: Dynamic UUIDs

App\Entity\Product:
  product1:
    id: '<uuidV4()>'
    sku: '<uuidV8(product1)>'

Event-Driven Workflows

Extend functionality with events:

  1. BeforeFixturesEvent: Modify fixture data before loading.
  2. AfterFixturesEvent: Perform actions post-load (e.g., log, trigger services).

Example Listener:

#[AsEventListener]
readonly class PostFixtureListener {
    public function __invoke(AfterFixturesEvent $event): void {
        $this->logger->info('Fixtures loaded. Triggering notifications...');
        // Custom logic (e.g., send welcome emails)
    }
}

Integration with Tests

Use fixtures in PHPUnit tests:

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class UserFixturesTest extends KernelTestCase {
    public function testUserCreation(): void {
        self::bootKernel();
        $this->loadFixtures(['config/fixtures/users.yaml']);
        $user = self::$container->get('doctrine')->getRepository(User::class)->findOneByEmail('user1@example.com');
        $this->assertNotNull($user);
    }
}

Gotchas and Tips

Common Pitfalls

  1. Circular References: Avoid bidirectional relationships in fixtures (e.g., UserPost where both reference each other). Use a clear hierarchy (e.g., load User first, then Post).

  2. UUID Collisions: If using <uuidV4()>, ensure uniqueness manually or via database constraints. Prefer <uuidV8(fixture_id)> for deterministic IDs.

  3. Event Dispatcher Conflicts: If using Symfony’s native event dispatcher, ensure AtournayreFixtureBundle is registered after your app’s bundles to avoid priority issues.

  4. Password Hashing: The <hashPassword()> provider uses Symfony’s PasswordHasher. Ensure your User entity’s password field is typed as string (not object or Password).

Debugging Tips

  • Dry Run: Use --dry-run flag to preview fixtures without loading:
    php bin/console fixtures --dry-run
    
  • Verbose Output: Enable debug mode for detailed logs:
    php bin/console fixtures -vv
    
  • Fixture Validation: Validate YAML syntax with a linter (e.g., yamllint).

Extension Points

  1. Custom Providers: Extend the bundle by creating a custom provider service. Example:

    # config/services.yaml
    services:
        App\Fixture\Provider\CustomProvider:
            tags: ['atournayre.fixture.provider']
    
  2. Override Default Providers: Replace built-in providers (e.g., DateTime) by binding your own service with the same tag:

    tags: ['atournayre.fixture.provider.datetime']
    
  3. Environment-Specific Fixtures: Use Symfony’s parameter system to load different fixtures per environment:

    # config/fixtures/dev.yaml (loaded only in dev)
    App\Entity\User:
      dev_user:
        email: 'dev@example.com'
    

Performance

  • Batch Loading: For large datasets, split fixtures into multiple files and load them sequentially.
  • Database Transactions: Wrap fixture loading in a transaction for atomicity:
    $entityManager->getConnection()->beginTransaction();
    try {
        $this->loadFixtures(['file1.yaml', 'file2.yaml']);
        $entityManager->getConnection()->commit();
    } catch (\Exception $e) {
        $entityManager->getConnection()->rollBack();
        throw $e;
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui