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

Import Export Bundle Laravel Package

akuma/import-export-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require akuma/import-export-bundle
    

    Add to AppKernel.php (Symfony 2.x) or config/bundles.php (Symfony 3+):

    new Akuma\ImportExportBundle\AkumaImportExportBundle(),
    
  2. First Use Case: Export Create a controller method to trigger an export:

    use Akuma\ImportExportBundle\Export\ExportManager;
    
    public function exportAction(ExportManager $exportManager)
    {
        $export = $exportManager->createExport('App\Entity\User');
        $export->addField('id', 'ID');
        $export->addField('email', 'Email');
        $export->setFileName('users_export.csv');
        return $exportManager->export($export);
    }
    
  3. First Use Case: Import Configure a form to handle file uploads, then process:

    use Akuma\ImportExportBundle\Import\ImportManager;
    
    public function importAction(Request $request, ImportManager $importManager)
    {
        $import = $importManager->createImport('App\Entity\User');
        $import->addField('email', 'Email');
        $import->addField('name', 'Name');
        $import->setFile($request->files->get('file'));
        return $importManager->import($import);
    }
    

Key Files to Review

  • Resources/config/services.yml (Symfony 2.x) or config/services.yaml (Symfony 3+): Service configurations.
  • Import/ImportManager.php and Export/ExportManager.php: Core logic for imports/exports.
  • Event/ImportEvents.php and Event/ExportEvents.php: Customization hooks.

Implementation Patterns

Common Workflows

Export Workflow

  1. Define Export Structure

    $export = $exportManager->createExport('App\Entity\User');
    $export->addField('id', 'ID', 'integer'); // Field, Header, Type
    $export->addField('email', 'Email Address', 'string');
    $export->setFileName('custom_users.csv');
    
  2. Customize Export Format Use events to modify output:

    $export->on('preExport', function ($event) {
        $event->getExport()->addRow(['id' => 1, 'email' => 'admin@example.com']);
    });
    
  3. Trigger Export

    return $exportManager->export($export, 'csv'); // Force format if needed
    

Import Workflow

  1. Define Import Mapping

    $import = $importManager->createImport('App\Entity\User');
    $import->addField('email', 'Email'); // Field in DB, Header in CSV
    $import->addField('name', 'Full Name');
    $import->setFile($request->files->get('file'));
    
  2. Validate Before Import

    $import->on('preImport', function ($event) {
        $data = $event->getData();
        if (empty($data[0]['email'])) {
            throw new \RuntimeException('Email is required.');
        }
    });
    
  3. Process Import

    $result = $importManager->import($import);
    // $result contains success/failure counts and errors
    

Integration with Symfony Forms

$form = $this->createFormBuilder()
    ->add('file', FileType::class, [
        'label' => 'CSV File',
        'required' => true,
    ])
    ->getForm();

Advanced Patterns

Dynamic Field Mapping

Use callbacks for dynamic field resolution:

$import->addField('email', function ($header) {
    return strtolower($header); // Normalize header
});

Batch Processing

For large imports/exports, use chunking:

$export->setChunkSize(100); // Process 100 records at a time

Custom Writers/Readers

Extend Akuma\ImportExportBundle\Writer\WriterInterface or Akuma\ImportExportBundle\Reader\ReaderInterface for custom formats (e.g., Excel, JSON).


Gotchas and Tips

Pitfalls

  1. PHP Version Compatibility

    • The package requires PHP 5.6+, but some dependencies (e.g., Symfony) may need newer PHP (7.1+). Test thoroughly.
  2. Memory Limits

    • Large exports/imports may hit memory limits. Use setChunkSize() or setMemoryLimit():
      $export->setMemoryLimit(512); // MB
      
  3. Field Name Sensitivity

    • Field names in headers must match the entity property names exactly (case-sensitive). Use callbacks for normalization:
      $import->addField('user_email', 'Email', function ($header) {
          return 'email'; // Map to entity property
      });
      
  4. Event Order

    • Events fire in this order: preExport/preImportpostExport/postImport. Avoid side effects in pre events that might break post logic.
  5. File Handling

    • Ensure uploaded files are validated for type/size before processing:
      $file = $request->files->get('file');
      if (!$file->isValid()) {
          throw new \RuntimeException('Invalid file upload.');
      }
      

Debugging Tips

  1. Enable Verbose Logging Configure Monolog to log import/export events:

    # config/packages/monolog.yaml
    handlers:
        import_export:
            type: stream
            path: "%kernel.logs_dir%/import_export.log"
            level: debug
    
  2. Check Event Subscribers If events aren’t firing, verify subscribers are registered in services.yaml:

    services:
        App\EventSubscriber\ImportSubscriber:
            tags:
                - { name: kernel.event_subscriber }
    
  3. Validate Entity Mappings Use the validateMapping() method to check field mappings before import/export:

    if (!$import->validateMapping()) {
        throw new \RuntimeException('Invalid field mappings: ' . $import->getErrors());
    }
    

Extension Points

  1. Custom Formats Extend AbstractWriter or AbstractReader:

    class JsonWriter extends AbstractWriter
    {
        public function write(array $data): string
        {
            return json_encode($data);
        }
    }
    

    Register as a service:

    services:
        Akuma\ImportExportBundle\Writer\JsonWriter:
            tags: { name: akuma_import_export.writer, alias: 'json' }
    
  2. Pre/Post Processing Use events for custom logic:

    $export->on('postExport', function ($event) {
        $event->getExport()->sendEmail('admin@example.com', 'Export ready!');
    });
    
  3. Database-Specific Optimizations For MySQL, add indexes to fields used in imports/exports to speed up bulk operations:

    // In a Doctrine migration
    $this->addSql('ALTER TABLE user ADD INDEX idx_email (email)');
    
  4. Localization Override field labels in translations:

    # config/packages/translation.yaml
    en:
        akuma_import_export:
            user:
                email: "User Email Address"
                name: "Full Name"
    
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.
besmartand-pro/php-quality-config
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