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

Export Bundle Laravel Package

bluetea/export-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer (if not archived, but since it is, check for forks or alternatives like league/csv + custom logic):

    composer require bluetea/export-bundle
    

    Note: Due to archival, verify compatibility with your Symfony version (likely Symfony2).

  2. Enable the Bundle in app/AppKernel.php:

    new BlueTea\ExportBundle\BlueTeaExportBundle(),
    
  3. Basic CSV Export Controller:

    use BlueTea\ExportBundle\Exporter\ExporterInterface;
    use BlueTea\ExportBundle\Exporter\CsvExporter;
    
    class ExportController extends Controller
    {
        public function exportAction()
        {
            $exporter = $this->get('blue_tea_export.exporter.csv');
            $data = $this->getDoctrine()->getRepository('AppBundle:User')->findAll();
    
            return $exporter->export($data, 'users.csv');
        }
    }
    
  4. Route the Controller:

    # app/config/routing.yml
    export_users:
        path:     /export/users
        defaults: { _controller: AppBundle:Export:export }
    

First Use Case

Export a Doctrine entity (e.g., User) to CSV with headers:

$exporter = $this->get('blue_tea_export.exporter.csv');
$users = $this->getDoctrine()->getRepository('AppBundle:User')->findAll();
$headers = ['ID', 'Email', 'Name']; // Map to entity properties

return $exporter->export($users, 'users.csv', $headers);

Implementation Patterns

Core Workflow

  1. Dependency Injection: Inject ExporterInterface (or CsvExporter directly) into services/controllers:

    public function __construct(ExporterInterface $exporter) {
        $this->exporter = $exporter;
    }
    
  2. Data Transformation: Use factories to format data before export. Example for custom objects:

    $factory = new \BlueTea\ExportBundle\Factory\ArrayFactory();
    $formattedData = $factory->transform($users); // Converts entities to arrays
    $this->exporter->export($formattedData, 'output.csv');
    
  3. Streaming Large Datasets: For memory efficiency, stream rows instead of loading all data:

    $query = $this->getDoctrine()->getRepository('AppBundle:User')->createQueryBuilder('u');
    $exporter->setStreamingMode(true);
    $exporter->export($query->getResult(), 'large_users.csv');
    
  4. Dynamic Headers: Auto-generate headers from Doctrine metadata:

    $metadata = $this->getDoctrine()->getManager()->getMetadataFactory()->getMetadataFor('AppBundle:User');
    $headers = array_map(function($field) { return $field->getName(); }, $metadata->getFieldNames());
    

Integration Tips

  • Symfony Forms: Attach exports to form actions:
    $form = $this->createFormBuilder()
        ->add('export', SubmitType::class, ['label' => 'Export CSV'])
        ->getForm();
    
    if ($form->isSubmitted() && $form->isValid()) {
        return $this->exportAction();
    }
    
  • Event Listeners: Trigger exports on entity lifecycle events (e.g., post-save):
    $eventManager->addEventListener(
        KernelEvents::TERMINATE,
        function () use ($exporter) {
            $exporter->export($data, 'audit.csv');
        }
    );
    
  • Custom Exporters: Extend AbstractExporter to support new formats (e.g., JSON):
    class JsonExporter extends AbstractExporter
    {
        protected function writeHeader(array $headers) { /* ... */ }
        protected function writeRow(array $row) { /* ... */ }
    }
    

Gotchas and Tips

Pitfalls

  1. Archived Status:

    • The bundle is unmaintained (last release: 2014). Test thoroughly or fork for updates.
    • Alternative: Use league/csv or matthiasnoback/symfony-export-bundle for modern Symfony.
  2. Doctrine Dependency:

    • Assumes Doctrine ORM. For non-Doctrine projects, mock repositories or use raw arrays.
  3. Memory Limits:

    • Large datasets may hit PHP memory limits. Use setStreamingMode(true) or chunk queries:
      $exporter->export(array_chunk($users, 1000), 'chunked_users.csv');
      
  4. Header Mismatch:

    • Headers must match data array keys. Use array_keys($data[0]) for auto-detection:
      $headers = array_keys(reset($users));
      
  5. Encoding Issues:

    • CSV may corrupt non-UTF-8 data. Force encoding:
      $exporter->setEncoding('UTF-8');
      

Debugging

  • Empty Output: Verify:
    • Data is not empty (count($data) > 0).
    • Headers match data structure.
    • No exceptions in writeRow() (check logs).
  • Permissions: Ensure web server can write to the output path (e.g., var/exports/).

Extension Points

  1. Custom Factories: Override ArrayFactory to transform complex objects:

    class UserFactory extends ArrayFactory
    {
        public function transform($user)
        {
            return [
                'id' => $user->getId(),
                'full_name' => $user->getFirstName() . ' ' . $user->getLastName(),
            ];
        }
    }
    
  2. Post-Export Actions: Hook into postExport event (if supported) or chain services:

    $exporter->export($data, 'file.csv');
    $this->mailer->send('export@ready@example.com', 'Export ready', ['file' => 'file.csv']);
    
  3. Configuration: Override defaults in config.yml:

    blue_tea_export:
        csv:
            delimiter: ';'
            enclosure: '"'
            escape_char: '\\'
            line_ending: "\r\n"
            include_headers: true
    

Pro Tips

  • Cache Exports: Store generated files in cache/ and clear on data changes.
  • Security: Validate user permissions before allowing exports:
    $this->denyAccessUnlessGranted('ROLE_EXPORT', $user);
    
  • Testing: Mock ExporterInterface in PHPUnit:
    $mockExporter = $this->createMock(ExporterInterface::class);
    $mockExporter->expects($this->once())->method('export');
    $this->controller->setExporter($mockExporter);
    
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
croct/coding-standard
croct/plug-php
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields