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

Alice Data Fixtures Laravel Package

theofidry/alice-data-fixtures

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require --dev theofidry/alice-data-fixtures

For Symfony Flex projects, run:

composer require --dev theofidry/alice-data-fixtures
php bin/console make:fixtures
  1. First Fixture File (database/fixtures/users.yml):

    App\Models\User:
      user1:
        name: 'John Doe'
        email: 'john@example.com'
        password: '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi'
    
  2. Load Fixtures:

    php bin/console fixtures:load
    

    For Eloquent (non-Symfony):

    php artisan db:seed --class=YourFixtureSeeder
    
  3. Verify:

    php bin/console doctrine:fixtures:load --append
    

    Or check your database directly.


First Use Case: Seeding Development Data

  • Use AliceDataFixtures to populate a local database with test users, posts, or products.
  • Example: Load a posts.yml fixture with relationships to pre-populated users.yml:
    App\Models\Post:
      post1:
        title: 'First Post'
        content: 'Hello World'
        user: '@user1'  # Reference to user1 from users.yml
    

Implementation Patterns

Workflow: Fixture Development

  1. Define Fixtures:

    • Use YAML/JSON/XML files in database/fixtures/ (Symfony) or database/fixtures/ (Laravel).
    • Leverage references (@user1) for relationships.
  2. Load Fixtures:

    • Symfony: php bin/console fixtures:load
    • Laravel: php artisan db:seed --class=YourSeeder
    • Use --append to add to existing data (avoids truncation).
  3. Organize Fixtures:

    • Group by domain (e.g., users.yml, posts.yml, roles.yml).
    • Use tags (tags: [users, admin]) to load subsets:
      php bin/console fixtures:load --tag=users
      
  4. Integration with Tests:

    • Load fixtures in setUp() for PHPUnit:
      public function setUp(): void {
          $this->loadFixtures(['users.yml', 'posts.yml']);
      }
      

Workflow: Relationships and Factories

  1. Complex Relationships:

    • Use nested fixtures for hierarchical data (e.g., categories with subcategories):
      App\Models\Category:
        electronics:
          name: 'Electronics'
          subcategories:
            - name: 'Phones'
            - name: 'Laptops'
      
  2. Dynamic Data:

    • Use faker expressions in fixtures:
      App\Models\User:
        user{1..10}:
          name: '<firstName> <lastName>'
          email: '<email>'
      
  3. Custom Factories:

    • Extend Alice’s factory system for reusable logic:
      // src/FixtureFactory.php
      public function createUserWithRole(string $roleName) {
          return $this->procedure('App\Models\User', [
              'name' => 'Admin',
              'email' => 'admin@example.com',
              'roles' => [$roleName],
          ]);
      }
      
  4. Seeding in Migrations:

    • Use fixtures to populate data after migrations:
      // database/migrations/...
      public function up() {
          Schema::create('users');
          $this->loadFixtures(['users.yml']);
      }
      

Integration Tips

  1. Symfony:

    • Register the bundle in config/bundles.php (if not using Flex).
    • Customize the loader in config/packages/nelmio_alice.yaml:
      nelmio_alice:
          fixtures:
              paths: ['%kernel.project_dir%/database/fixtures']
              loaded_fixtures: 'database/fixtures/loaded_fixtures.yml'
      
  2. Laravel:

    • Publish the config (if needed) and bind the loader to the container:
      $this->app->bind('fixtures.loader', function ($app) {
          return new \Theofidry\AliceDataFixtures\Loader\Loader(
              $app['path.database'].'/fixtures',
              $app['path.database'].'/fixtures/loaded_fixtures.yml'
          );
      });
      
  3. Doctrine Events:

    • Trigger fixture loading after database events (e.g., postInstall):
      # config/packages/doctrine.yaml
      doctrine:
          dbal:
              connections:
                  default:
                      events:
                          postInstall: ['fixtures:load']
      
  4. CI/CD:

    • Load fixtures in CI pipelines to ensure consistent test environments:
      # .github/workflows/tests.yml
      - run: php bin/console fixtures:load --env=test
      

Gotchas and Tips

Pitfalls

  1. Duplicate Data:

    • AliceDataFixtures checks for duplicates by default. To override:
      # config/packages/nelmio_alice.yaml
      nelmio_alice:
          persistence:
              orm:
                  truncate: false  # Allow duplicates
      
  2. Transaction Failures:

    • Large fixtures may hit transaction limits. Use --no-transaction:
      php bin/console fixtures:load --no-transaction
      
  3. Circular References:

    • Avoid circular references (e.g., User referencing Post which references User). Use lazy loading or break cycles:
      App\Models\User:
        user1:
          posts: ['@post1', '@post2']  # Ensure posts exist first
      
  4. Eloquent vs. Doctrine:

    • Eloquent requires explicit model binding. Ensure your models are auto-discovered:
      // config/app.php
      'providers' => [
          Illuminate\Database\Eloquent\Model::class,
      ],
      

Debugging

  1. Dry Run:

    • Preview fixtures without loading:
      php bin/console fixtures:load --dry-run
      
  2. Verbose Output:

    • Enable debug mode for detailed logs:
      php bin/console fixtures:load -vvv
      
  3. Loaded Fixtures File:

    • Check database/fixtures/loaded_fixtures.yml to verify what was loaded.
  4. Doctrine Events:

    • Debug event listeners if fixtures aren’t loading:
      php bin/console debug:event-dispatcher
      

Tips

  1. Partial Loading:

    • Load only specific fixtures by name:
      php bin/console fixtures:load --fixtures=users.yml,posts.yml
      
  2. Environment-Specific Fixtures:

    • Use different fixture paths per environment:
      # config/packages/nelmio_alice.yaml
      nelmio_alice:
          fixtures:
              paths:
                  '%kernel.environment%': '%kernel.project_dir%/database/fixtures/%kernel.environment%'
      
  3. Custom Loaders:

    • Extend the loader for custom logic (e.g., pre-processing):
      class CustomLoader extends \Theofidry\AliceDataFixtures\Loader\Loader {
          public function load(array $fixtures) {
              // Pre-process fixtures here
              parent::load($fixtures);
          }
      }
      
  4. Performance:

    • Disable persistence for non-critical fixtures:
      # config/packages/nelmio_alice.yaml
      nelmio_alice:
          persistence:
              orm:
                  enabled: false
      
  5. Testing:

    • Reset fixtures between tests:
      public function tearDown(): void {
          $this->loadFixtures(['--purge' => true]);
      }
      
  6. PHPCR/ODM:

    • For Doctrine ODM/PHPCR, ensure your fixture paths are correct and use the appropriate loader:
      nelmio_alice:
          persistence:
              odm:
                  enabled: true
      
  7. Seeding in Production:

    • Never load fixtures in production. Use environment checks:
      if (app()->environment('production')) {
          throw new \RuntimeException('Fixtures cannot be loaded in production.');
      }
      
  8. Custom References:

    • Use custom reference resolvers for dynamic data:
      $loader->setReferenceResolver(new CustomReferenceResolver());
      
  9. Fixture Validation:

    • Validate YAML syntax with:
      php bin/console debug:container --parameter=nelmio_alice.fixtures.paths
      
  10. **Backup Before

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