PHP code example of ecourty / doctrine-export-bundle
1. Go to this page and download the library: Download ecourty/doctrine-export-bundle library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ecourty / doctrine-export-bundle example snippets
// config/bundles.php
return [
// ...
Ecourty\DoctrineExportBundle\DoctrineExportBundle::class => ['all' => true],
];
use Ecourty\DoctrineExportBundle\Contract\DoctrineExporterInterface;
use Ecourty\DoctrineExportBundle\Enum\ExportFormat;
// Inject the service
public function __construct(
private DoctrineExporterInterface $exporter
) {}
// Export to CSV
$this->exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::CSV,
filePath: '/tmp/users.csv'
);
// Stream to browser
return new StreamedResponse(
$this->exporter->exportToGenerator(User::class, ExportFormat::JSON),
Response::HTTP_OK,
['Content-Type' => 'application/json']
);
use Ecourty\DoctrineExportBundle\Contract\DoctrineExporterInterface;
use Ecourty\DoctrineExportBundle\Enum\ExportFormat;
use App\Entity\User;
class UserExportService
{
public function __construct(
private DoctrineExporterInterface $exporter
) {}
public function exportActiveUsers(): void
{
$this->exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::CSV,
filePath: '/tmp/active_users.csv',
criteria: ['isActive' => true],
limit: 1000,
orderBy: ['createdAt' => 'DESC']
);
}
}
use Symfony\Component\HttpFoundation\StreamedResponse;
#[Route('/export/users')]
public function export(DoctrineExporterInterface $exporter): StreamedResponse
{
$format = ExportFormat::CSV;
return new StreamedResponse(
$exporter->exportToGenerator(
entityClass: User::class,
format: $format,
criteria: ['isActive' => true]
),
200,
[
'Content-Type' => $format->getMimeType(),
'Content-Disposition' => 'attachment; filename="users.' . $format->getExtension() . '"'
]
);
}
use Ecourty\DoctrineExportBundle\Event\PostExportEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
#[AsEventListener]
public function onPostExport(PostExportEvent $event): void
{
$this->logger->info('Export completed', [
'entity' => $event->getEntityClass(),
'count' => $event->getExportedCount(),
]);
}
use Ecourty\DoctrineExportBundle\Event\PostExportEvent;
#[AsEventListener]
public function onPostExport(PostExportEvent $event): void
{
$duration = $event->getDurationInSeconds();
$throughput = $event->getExportedCount() / $duration;
$this->metrics->gauge('export.duration', $duration);
$this->metrics->gauge('export.throughput', $throughput);
}
// CSV
$exporter->exportToFile(User::class, ExportFormat::CSV, '/tmp/users.csv');
// JSON
$exporter->exportToFile(User::class, ExportFormat::JSON, '/tmp/users.json');
// XML
$exporter->exportToFile(User::class, ExportFormat::XML, '/tmp/users.xml');
use Ecourty\DoctrineExportBundle\Contract\EntityProcessorInterface;
class EmailMaskingProcessor implements EntityProcessorInterface
{
public function process(object $entity, array $data, array $options): array
{
// Mask email addresses
if (isset($data['email'])) {
$data['email'] = preg_replace('/(?<=.).(?=.*@)/', '*', $data['email']);
}
return $data;
}
}
$exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::CSV,
filePath: '/tmp/users.csv',
processors: [new EmailMaskingProcessor()]
);
class UserVirtualFieldsProcessor implements EntityProcessorInterface
{
public function process(object $entity, array $data, array $options): array
{
assert($entity instanceof User);
// Add computed fields
$data['displayName'] = $entity->getFirstName() . ' ' . $entity->getLastName();
$data['ageCategory'] = $entity->getAge() >= 30 ? 'senior' : 'junior';
return $data;
}
}
// Export with virtual fields
$exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::JSON,
filePath: '/tmp/users.json',
fields: ['firstName', 'displayName', 'ageCategory'], // Include virtual fields
processors: [new UserVirtualFieldsProcessor()]
);
$exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::CSV,
filePath: '/tmp/users.csv',
processors: [
new EmailMaskingProcessor(), // First: mask emails
new UppercaseProcessor(), // Then: uppercase all strings
new UserVirtualFieldsProcessor(), // Finally: add virtual fields
]
);
class FullyCustomProcessor implements EntityProcessorInterface
{
public function process(object $entity, array $data, array $options): array
{
// Handle ALL field extraction yourself
$data['id'] = $entity->getId();
$data['email'] = $entity->getEmail();
// ... handle all fields
return $data;
}
}
$exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::JSON,
filePath: '/tmp/users.json',
fields: ['id', 'email'],
options: [
// Skip default processor - custom processor handles everything
DoctrineExporterInterface::OPTION_DISABLE_DEFAULT_PROCESSOR => true,
],
processors: [new FullyCustomProcessor()]
);
// Export only specific fields
$exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::CSV,
filePath: '/tmp/users_minimal.csv',
fields: ['id', 'email', 'firstName', 'lastName'] // Only these fields
);
// Export all fields (default)
$exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::CSV,
filePath: '/tmp/users_full.csv',
fields: [] // Empty = all fields
);
use Ecourty\DoctrineExportBundle\Contract\DoctrineExporterInterface;
$exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::CSV,
filePath: '/tmp/users.csv',
options: [
// Boolean values as integers (default: true)
DoctrineExporterInterface::OPTION_BOOLEAN_TO_INTEGER => false,
// Custom datetime format (default: ATOM)
DoctrineExporterInterface::OPTION_DATETIME_FORMAT => 'Y-m-d H:i:s',
// Custom null value representation (default: null)
DoctrineExporterInterface::OPTION_NULL_VALUE => '',
// Strict field validation - throw exception if field doesn't exist (default: false)
DoctrineExporterInterface::OPTION_STRICT_FIELDS => true,
// Disable default processor for performance (default: false)
// Only use when custom processor handles all data extraction
DoctrineExporterInterface::OPTION_DISABLE_DEFAULT_PROCESSOR => true,
]
);
// This will throw InvalidCriteriaException if 'nonExistentField' doesn't exist
$exporter->exportToFile(
entityClass: User::class,
format: ExportFormat::CSV,
filePath: '/tmp/users.csv',
criteria: ['nonExistentField' => 'value'] // ❌ Throws exception
);
// Streaming export - automatically memory efficient
foreach ($exporter->exportToGenerator(User::class, ExportFormat::CSV) as $line) {
echo $line; // Each entity is processed and immediately detached
flush();
}
// Given entities:
// Article (id, title, author_id) -> ManyToOne -> User (id, name)
// Article (id, title) -> ManyToMany -> Tag (id, name)
$exporter->exportToFile(
entityClass: Article::class,
format: ExportFormat::JSON,
filePath: '/tmp/articles.json',
fields: ['title', 'author', 'tags']
);
// Output:
// [
// {"title": "Article 1", "author": 42, "tags": [1, 2, 3]},
// {"title": "Article 2", "author": 43, "tags": [2, 4]}
// ]