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 Mapper Bundle Laravel Package

codixis/fixtures-mapper-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require codixis/fixtures-mapper-bundle
    

    Enable it in config/bundles.php:

    Codixis\FixturesMapperBundle\CodixisFixturesMapperBundle::class => ['all' => true],
    
  2. Basic Configuration Update config/packages/codixis_fixtures_mapper.yaml (create if missing):

    codixis_fixtures_mapper:
        fixtures_dir: '%kernel.project_dir%/data/fixtures'
        formats: ['csv', 'yaml']
    
  3. First Fixture File Create a CSV file at data/fixtures/users.csv:

    id,name,email
    1,John Doe,john@example.com
    2,Jane Smith,jane@example.com
    
  4. Load Fixtures via CLI Use the fixtures:load command:

    php bin/console fixtures:load
    

First Use Case: Loading CSV Fixtures

  1. Define a Mapper Class Create a mapper for your User entity in src/DataFixtures/Mapper/UserMapper.php:

    namespace App\DataFixtures\Mapper;
    
    use Codixis\FixturesMapperBundle\Mapper\FixturesMapperInterface;
    use Doctrine\Common\Persistence\ObjectManager;
    
    class UserMapper implements FixturesMapperInterface
    {
        public function map(array $data, ObjectManager $manager)
        {
            $user = new \App\Entity\User();
            $user->setId($data['id']);
            $user->setName($data['name']);
            $user->setEmail($data['email']);
            $manager->persist($user);
        }
    }
    
  2. Register the Mapper Update config/packages/codixis_fixtures_mapper.yaml:

    codixis_fixtures_mapper:
        mappers:
            user:
                class: App\DataFixtures\Mapper\UserMapper
                file: users.csv
    
  3. Load Specific Fixtures

    php bin/console fixtures:load user
    

Implementation Patterns

Workflow: Fixture Development

  1. File Structure Organize fixtures by entity/module:

    data/fixtures/
    ├── users/
    │   ├── users.csv
    │   └── users.yaml
    └── products/
        ├── products.csv
        └── products.yaml
    
  2. YAML Fixtures Example products.yaml:

    products:
        product_1:
            name: "Laptop"
            price: 999.99
            stock: 10
        product_2:
            name: "Phone"
            price: 699.99
            stock: 20
    
  3. Mapper for YAML

    namespace App\DataFixtures\Mapper;
    
    use Codixis\FixturesMapperBundle\Mapper\FixturesMapperInterface;
    use Doctrine\Common\Persistence\ObjectManager;
    
    class ProductMapper implements FixturesMapperInterface
    {
        public function map(array $data, ObjectManager $manager)
        {
            foreach ($data['products'] as $productData) {
                $product = new \App\Entity\Product();
                $product->setName($productData['name']);
                $product->setPrice($productData['price']);
                $product->setStock($productData['stock']);
                $manager->persist($product);
            }
        }
    }
    

Integration Tips

  1. Dependency Injection Inject the FixturesMapper service in controllers/services:

    use Codixis\FixturesMapperBundle\Service\FixturesMapper;
    
    class SomeService
    {
        public function __construct(private FixturesMapper $fixturesMapper) {}
    
        public function loadTestData()
        {
            $this->fixturesMapper->load('user');
        }
    }
    
  2. Custom Fixture Directories Override fixtures_dir per environment:

    # config/packages/dev/codixis_fixtures_mapper.yaml
    codixis_fixtures_mapper:
        fixtures_dir: '%kernel.project_dir%/data/fixtures/dev'
    
  3. Partial Loads Use --filter to load specific records (CSV only):

    php bin/console fixtures:load user --filter="name=John"
    
  4. Post-Load Actions Extend the FixturesMapper to run logic after loading:

    $this->fixturesMapper->load('user', function() {
        // Run post-load logic (e.g., send welcome emails)
    });
    

Gotchas and Tips

Pitfalls

  1. Unmaintained Package

    • No active maintenance; expect no bug fixes or updates.
    • Fork and maintain locally if critical for your project.
  2. CSV Parsing Quirks

    • Delimiters: Defaults to comma (,). Use --delimiter for custom delimiters:
      php bin/console fixtures:load user --delimiter=";"
      
    • Escaping: CSV fields with commas (e.g., "New York, NY") must be quoted. Test edge cases.
  3. YAML Anchors & References

    • Avoid YAML anchors (&) and references (*) as they may not map cleanly to arrays.
  4. Doctrine Events

    • Fixtures load in a single transaction. Avoid relying on Doctrine lifecycle events (e.g., prePersist) for critical logic.
  5. Overwriting Data

    • By default, fixtures are not deleted before loading. Use --delete to truncate tables first:
      php bin/console fixtures:load user --delete
      

Debugging

  1. Dry Run Mode Enable verbose output to see what would be loaded:

    php bin/console fixtures:load user --dry-run
    
  2. Logging Configure Monolog to log fixture loading:

    # config/packages/monolog.yaml
    handlers:
        fixtures:
            type: stream
            path: "%kernel.logs_dir%/fixtures.log"
            level: debug
    
  3. Mapper Errors

    • Check for FixturesMapperException in logs if mapping fails.
    • Validate CSV/YAML structure with tools like CSVLint or YAML Lint.

Extension Points

  1. Custom Format Support Extend the bundle to support JSON or XML by implementing Codixis\FixturesMapperBundle\Loader\LoaderInterface:

    namespace App\Fixtures\Loader;
    
    use Codixis\FixturesMapperBundle\Loader\LoaderInterface;
    
    class JsonLoader implements LoaderInterface
    {
        public function load(string $file): array
        {
            return json_decode(file_get_contents($file), true);
        }
    }
    

    Register in config:

    codixis_fixtures_mapper:
        loaders:
            json: App\Fixtures\Loader\JsonLoader
    
  2. Pre/Post Load Hooks Subscribe to the fixtures_mapper.load event:

    namespace App\EventListener;
    
    use Codixis\FixturesMapperBundle\Event\FixturesLoadEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class FixturesSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'fixtures_mapper.load' => 'onFixturesLoad',
            ];
        }
    
        public function onFixturesLoad(FixturesLoadEvent $event)
        {
            // Run before/after loading
        }
    }
    
  3. Dynamic Fixtures Generate fixtures dynamically by implementing FixturesMapperInterface with runtime logic:

    class DynamicUserMapper implements FixturesMapperInterface
    {
        public function map(array $data, ObjectManager $manager)
        {
            for ($i = 1; $i <= 100; $i++) {
                $user = new User();
                $user->setName("User $i");
                $user->setEmail("user$i@example.com");
                $manager->persist($user);
            }
        }
    }
    

Configuration Quirks

  1. Case Sensitivity

    • Fixture file names and mapper keys are case-sensitive in YAML/CSV headers.
  2. Default Values

    • Missing CSV/YAML fields default to null. Handle in your mapper:
      $user->setEmail($data['email'] ?? 'default@example.com');
      
  3. Environment Variables

    • Use %env() in config for dynamic paths:
      codixis_fixtures_mapper:
          fixtures_dir: '%env(FIxtures_DIR)%/data'
      
  4. Caching

    • Disable caching for development:
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky