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

sylius/fixtures-bundle

Sylius Fixtures Bundle provides configurable data fixtures for Symfony apps. Define and load structured demo or test data through flexible configuration, ideal for seeding development environments and repeatable setups.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sylius/fixtures-bundle
    

    Ensure your config/packages/dev/sylius_fixtures.yaml exists (or create it).

  2. Define Fixtures: Create a YAML file (e.g., config/fixtures/users.yaml):

    App\DataFixtures\ORM\UserFixtures:
        resources:
            - 'data/users.yml'
    
  3. Load Fixtures:

    php bin/console sylius:fixtures:load
    

    Or load a specific suite:

    php bin/console sylius:fixtures:load --suite=users
    

First Use Case: Populating a Development Database

  • Use the bundle to seed your database with test data (e.g., users, products, orders) during local development.
  • Example workflow:
    # Clear existing data (optional)
    php bin/console doctrine:database:drop --force
    php bin/console doctrine:database:create
    
    # Load fixtures
    php bin/console sylius:fixtures:load
    

Implementation Patterns

Fixture Structure

  1. Fixtures Classes: Extend Sylius\Bundle\FixturesBundle\Fixture\AbstractFixture or implement Sylius\Bundle\FixturesBundle\Fixture\FixtureInterface. Example:

    namespace App\DataFixtures\ORM;
    
    use Sylius\Bundle\FixturesBundle\Fixture\AbstractFixture;
    use Doctrine\Common\DataFixtures\Purger\ORMPurger;
    use Doctrine\Common\Persistence\ObjectManager;
    
    class UserFixtures extends AbstractFixture
    {
        public function load(ObjectManager $manager): void
        {
            $user = new User();
            $user->setEmail('test@example.com');
            $manager->persist($user);
        }
    
        public function getDependencies(): array
        {
            return [];
        }
    }
    
  2. YAML Configuration: Define fixture suites in config/fixtures/*.yaml:

    App\DataFixtures\ORM\UserFixtures:
        resources:
            - 'data/users.yml'
        options:
            purge_mode: DELETE_ORPHAN
    
  3. Dependency Management: Use getDependencies() to define fixture load order:

    public function getDependencies(): array
    {
        return [ProductFixtures::class];
    }
    

Workflows

  1. Partial Loading: Load only specific fixtures:

    php bin/console sylius:fixtures:load --fixtures=UserFixtures
    
  2. Environment-Specific Fixtures: Use environment variables to toggle fixture loading:

    # config/packages/dev/sylius_fixtures.yaml
    sylius_fixtures:
        suites:
            default:
                fixtures:
                    - App\DataFixtures\ORM\UserFixtures
                    - App\DataFixtures\ORM\ProductFixtures
    
  3. Custom Fixture Loaders: Implement Sylius\Bundle\FixturesBundle\Fixture\Loader\LoaderInterface for custom logic (e.g., API-based fixtures).

Integration Tips

  1. Doctrine Events: Listen to sylius_fixtures.load events for post-load actions:

    use Sylius\Bundle\FixturesBundle\Event\FixturesEvent;
    
    public function onFixturesLoaded(FixturesEvent $event): void
    {
        $this->logger->info('Fixtures loaded!');
    }
    
  2. Symfony Console Commands: Extend Sylius\Bundle\FixturesBundle\Command\LoadFixturesCommand for custom commands.

  3. Testing: Use fixtures in PHPUnit tests:

    use Sylius\Bundle\FixturesBundle\Fixture\Loader\FixturesLoaderInterface;
    
    public function testSomething(FixturesLoaderInterface $loader)
    {
        $loader->load('default');
        // Test logic here
    }
    

Gotchas and Tips

Pitfalls

  1. Purge Mode Conflicts:

    • DELETE_ORPHAN may remove unintended data. Use TRUNCATE for a clean slate (but be cautious with foreign keys).
    • Debug with:
      php bin/console sylius:fixtures:load --dry-run
      
  2. Fixture Dependencies:

    • Circular dependencies will fail silently. Use getDependencies() carefully and validate with:
      php bin/console debug:fixtures
      
  3. Database Transactions:

    • Fixtures run in a transaction by default. Disable with:
      options:
          transaction: false
      

Debugging

  1. Verbose Output: Enable debug mode for detailed logs:

    php bin/console sylius:fixtures:load -vvv
    
  2. Fixture Validation: Validate YAML syntax and paths. Use:

    php bin/console debug:config sylius_fixtures
    
  3. Doctrine Events: Ensure your listeners are tagged correctly in services.yaml:

    tags:
        - { name: kernel.event_listener, event: sylius_fixtures.load, method: onFixturesLoaded }
    

Tips

  1. Reusable Fixtures: Use traits or base classes to avoid duplication:

    trait FixtureTrait
    {
        protected function createUser(string $email): User
        {
            $user = new User();
            $user->setEmail($email);
            return $user;
        }
    }
    
  2. Environment-Specific Data: Load different fixtures per environment:

    # config/packages/test/sylius_fixtures.yaml
    sylius_fixtures:
        suites:
            test:
                fixtures:
                    - App\DataFixtures\ORM\TestUserFixtures
    
  3. Performance:

    • Batch inserts for large datasets:
      $manager->flush();
      $manager->clear();
      
    • Use ORDER BY in YAML for predictable loading:
      options:
          order_by: [id]
      
  4. Custom Listeners: Extend functionality with listeners (e.g., post-load data transformation):

    use Sylius\Bundle\FixturesBundle\Event\FixturesEvent;
    use Sylius\Bundle\FixturesBundle\Event\FixturesEvents;
    
    class CustomListener
    {
        public function onFixturesLoaded(FixturesEvent $event)
        {
            // Custom logic here
        }
    }
    

    Register in services.yaml:

    services:
        App\EventListener\CustomListener:
            tags:
                - { name: kernel.event_listener, event: sylius_fixtures.load, method: onFixturesLoaded }
    
  5. Fixtures in Docker: Use entrypoint scripts to load fixtures on container startup:

    CMD php bin/console sylius:fixtures:load && php-fpm
    
  6. Backup Before Loading: Automate backups before fixture loads in CI/CD:

    php bin/console doctrine:database:backup
    php bin/console sylius:fixtures:load
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle