Installation
composer require akuma/import-export-bundle
Add to AppKernel.php (Symfony 2.x) or config/bundles.php (Symfony 3+):
new Akuma\ImportExportBundle\AkumaImportExportBundle(),
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);
}
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);
}
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.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');
Customize Export Format Use events to modify output:
$export->on('preExport', function ($event) {
$event->getExport()->addRow(['id' => 1, 'email' => 'admin@example.com']);
});
Trigger Export
return $exportManager->export($export, 'csv'); // Force format if needed
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'));
Validate Before Import
$import->on('preImport', function ($event) {
$data = $event->getData();
if (empty($data[0]['email'])) {
throw new \RuntimeException('Email is required.');
}
});
Process Import
$result = $importManager->import($import);
// $result contains success/failure counts and errors
$form = $this->createFormBuilder()
->add('file', FileType::class, [
'label' => 'CSV File',
'required' => true,
])
->getForm();
Use callbacks for dynamic field resolution:
$import->addField('email', function ($header) {
return strtolower($header); // Normalize header
});
For large imports/exports, use chunking:
$export->setChunkSize(100); // Process 100 records at a time
Extend Akuma\ImportExportBundle\Writer\WriterInterface or Akuma\ImportExportBundle\Reader\ReaderInterface for custom formats (e.g., Excel, JSON).
PHP Version Compatibility
Memory Limits
setChunkSize() or setMemoryLimit():
$export->setMemoryLimit(512); // MB
Field Name Sensitivity
$import->addField('user_email', 'Email', function ($header) {
return 'email'; // Map to entity property
});
Event Order
preExport/preImport → postExport/postImport. Avoid side effects in pre events that might break post logic.File Handling
$file = $request->files->get('file');
if (!$file->isValid()) {
throw new \RuntimeException('Invalid file upload.');
}
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
Check Event Subscribers
If events aren’t firing, verify subscribers are registered in services.yaml:
services:
App\EventSubscriber\ImportSubscriber:
tags:
- { name: kernel.event_subscriber }
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());
}
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' }
Pre/Post Processing Use events for custom logic:
$export->on('postExport', function ($event) {
$event->getExport()->sendEmail('admin@example.com', 'Export ready!');
});
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)');
Localization Override field labels in translations:
# config/packages/translation.yaml
en:
akuma_import_export:
user:
email: "User Email Address"
name: "Full Name"
How can I help you explore Laravel packages today?