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

Doctrine Export Bundle Laravel Package

ecourty/doctrine-export-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ecourty/doctrine-export-bundle
    

    Enable the bundle in config/bundles.php if not using Symfony Flex.

  2. First Export: Use the ExportService to export entities to CSV:

    use Ecourty\DoctrineExportBundle\Service\ExportService;
    
    $exportService = $this->container->get(ExportService::class);
    $entities = $entityManager->getRepository(Entity::class)->findAll();
    
    $exportService->exportToFile($entities, 'csv', 'output.csv');
    
  3. Quick Controller Example:

    use Symfony\Component\HttpFoundation\Response;
    use Ecourty\DoctrineExportBundle\Service\ExportService;
    
    #[Route('/export', name: 'export')]
    public function export(ExportService $exportService, EntityManagerInterface $em): Response
    {
        $entities = $em->getRepository(Entity::class)->findAll();
        return $exportService->exportToBinaryResponse($entities, 'csv', 'export.csv');
    }
    

Where to Look First

  • Service Class: Ecourty\DoctrineExportBundle\Service\ExportService (core functionality).
  • Configuration: config/packages/doctrine_export.yaml (if created).
  • Events: Ecourty\DoctrineExportBundle\Event\ExportEvents (for custom logic).

Implementation Patterns

Common Workflows

  1. Basic Export to File:

    $exportService->exportToFile($entities, 'csv', 'path/to/file.csv');
    
  2. Streaming Binary Response (for large datasets):

    return $exportService->exportToBinaryResponse($entities, 'json', 'data.json');
    
  3. Custom Field Mapping:

    $exportService->exportToFile(
        $entities,
        'csv',
        'output.csv',
        ['fields' => ['id', 'name', 'createdAt as date']]
    );
    
  4. Using Events for Pre/Post Processing:

    // Subscribe to events in a listener
    $dispatcher->addListener(
        ExportEvents::PRE_EXPORT,
        fn (ExportEvent $event) => $event->setData($event->getData() + ['custom_field' => true])
    );
    

Integration Tips

  • Doctrine QueryBuilder: Use findBy() or createQueryBuilder() to filter entities before export.
  • Symfony Forms: Bind export options to a form for user-configurable exports.
  • Cron Jobs: Schedule exports via Symfony Messenger or a cron job.
  • API Endpoints: Return exports as binary responses with proper headers:
    return new Response(
        $exportService->exportToBinary($entities, 'csv'),
        200,
        ['Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment; filename="export.csv"']
    );
    

Advanced Patterns

  • Custom Processors: Extend Ecourty\DoctrineExportBundle\Processor\EntityProcessorInterface for complex transformations.
  • Batch Processing: Use exportToStream() for memory-efficient large exports:
    $stream = $exportService->exportToStream($entities, 'csv');
    file_put_contents('large_export.csv', $stream);
    

Gotchas and Tips

Pitfalls

  1. Memory Issues:

    • Avoid loading all entities at once for large datasets. Use findBy() with pagination or exportToStream().
    • Example: findBy([], null, 1000) to fetch in chunks.
  2. Circular References:

    • Associations with circular references (e.g., User->Posts->User) may cause infinite loops. Use association_handling: 'ignore' in options:
      $exportService->exportToFile($entities, 'json', 'output.json', ['association_handling' => 'ignore']);
      
  3. Field Naming Conflicts:

    • Fields with special characters (e.g., field-name) may break CSV/JSON. Use fields option to alias:
      ['fields' => ['id', 'field-name as custom_field']]
      
  4. Timezone Handling:

    • Dates may serialize incorrectly if timezones aren’t set. Configure in config/packages/doctrine_export.yaml:
      doctrine_export:
          default_timezone: 'UTC'
      

Debugging Tips

  • Enable Debug Mode: Set debug: true in config to log export events.
  • Check Events: Listen to ExportEvents::POST_EXPORT to inspect the final output:
    $dispatcher->addListener(ExportEvents::POST_EXPORT, function (ExportEvent $event) {
        error_log('Exported data:', $event->getData());
    });
    
  • Validate Entities: Use field_validation: true to skip invalid entities during export.

Extension Points

  1. Custom Formats:

    • Implement Ecourty\DoctrineExportBundle\Writer\WriterInterface for new formats (e.g., Excel).
    • Register the writer in the bundle’s configuration.
  2. Dynamic Field Selection:

    • Use the fields option dynamically based on user input or roles:
      $fields = $this->getFieldsBasedOnUserRole($user);
      $exportService->exportToFile($entities, 'csv', 'output.csv', ['fields' => $fields]);
      
  3. Post-Export Actions:

    • Subscribe to ExportEvents::POST_EXPORT to trigger notifications, archive files, or send emails:
      $dispatcher->addListener(ExportEvents::POST_EXPORT, function (ExportEvent $event) {
          $this->mailer->sendEmail('user@example.com', 'Export Ready', 'File attached', ['file' => $event->getFilePath()]);
      });
      
  4. Performance Tuning:

    • Disable hydration for large exports:
      $entities = $em->getRepository(Entity::class)->findAll(); // No DTOs, use raw arrays
      $exportService->exportToFile($entities, 'csv', 'output.csv', ['hydrate' => false]);
      

Configuration Quirks

  • Default Options: Override defaults in config/packages/doctrine_export.yaml:
    doctrine_export:
        default_format: 'csv'
        default_options:
            fields: ['id', 'name']
            association_handling: 'ignore'
    
  • Case Sensitivity: Field names in fields option are case-sensitive unless configured otherwise. Use field_mapping for case-insensitive aliases.
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
spatie/mailcoach-vapor