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

Csv Bundle Laravel Package

ajgl/csv-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ajgl/csv-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3.x):

    // config/bundles.php
    return [
        // ...
        Ajgl\CsvBundle\AjglCsvBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Import the Ajgl\Csv\Csv class and use it to parse a CSV file:

    use Ajgl\Csv\Csv;
    
    $csv = new Csv();
    $data = $csv->parse(file_get_contents('path/to/file.csv'));
    

    Or generate a CSV from an array:

    $csv = new Csv();
    $csvContent = $csv->generate($dataArray);
    

Implementation Patterns

Common Workflows

  1. Parsing CSV Files:

    $csv = new Csv();
    $data = $csv->parse(file_get_contents('input.csv'), ',', '"');
    
    • Options: Pass delimiters, enclosures, and encoding (e.g., utf-8).
    • Streaming Large Files: Use parseStream() for memory efficiency:
      $stream = fopen('large_file.csv', 'r');
      $data = $csv->parseStream($stream);
      
  2. Generating CSV:

    $csv = new Csv();
    $csvContent = $csv->generate([
        ['Name', 'Email'],
        ['John', 'john@example.com'],
    ], ',', '"');
    
    • Headers: Automatically add headers if $data is associative.
    • Encoding: Specify encoding (e.g., utf-8) for non-ASCII characters.
  3. Integration with Symfony Services:

    • Register the Ajgl\Csv\Csv service in config/services.yaml:
      services:
          Ajgl\Csv\Csv: ~
      
    • Inject it into controllers or services:
      public function __construct(private Csv $csv) {}
      
  4. Command-Line Usage:

    • Use in console commands for batch processing:
      use Symfony\Component\Console\Command\Command;
      use Symfony\Component\Console\Input\InputInterface;
      use Symfony\Component\Console\Output\OutputInterface;
      
      class ImportCsvCommand extends Command
      {
          protected function execute(InputInterface $input, OutputInterface $output)
          {
              $csv = new Csv();
              $data = $csv->parse(file_get_contents($this->getInputFile()));
              // Process $data...
          }
      }
      
  5. Form Handling:

    • Validate and parse CSV uploads in forms:
      public function uploadAction(Request $request)
      {
          $file = $request->files->get('csv_file');
          $csv = new Csv();
          $data = $csv->parse($file->getContent());
          // Validate and save $data...
      }
      

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle:

    • Last release in 2016; no active maintenance. Use alternatives like league/csv for modern projects.
    • Symfony 5+: Incompatible due to dropped support for older Symfony versions.
  2. Memory Issues:

    • parse() loads the entire file into memory. For large files, always use parseStream():
      $stream = fopen('large.csv', 'r');
      $data = $csv->parseStream($stream);
      
  3. Encoding Problems:

    • Default encoding may not handle special characters (e.g., é, ü). Explicitly set encoding:
      $csv->parse($content, ',', '"', 'utf-8');
      
  4. Configuration Overrides:

    • Bundle uses legacy Symfony 2.x configuration. For Symfony 3/4, rely on autowiring or manual service registration.
  5. No Built-in Validation:

    • The bundle lacks schema validation. Manually validate parsed data or use a library like symfony/validator.

Debugging Tips

  1. Check Delimiters/Enclosures:

    • Common issues arise from incorrect delimiters (e.g., ; vs ,) or enclosures (e.g., " vs '). Inspect the CSV file manually or use a tool like CSVLint.
  2. Streaming Errors:

    • Ensure streams are properly closed:
      $stream = fopen('file.csv', 'r');
      try {
          $data = $csv->parseStream($stream);
      } finally {
          fclose($stream);
      }
      
  3. Symfony Dependency Conflicts:

    • If using Symfony 4+, ensure symfony/framework-bundle:^4.1 is installed (not older versions).

Extension Points

  1. Custom Parsing Logic:

    • Extend the Ajgl\Csv\Csv class to add custom parsing rules:
      class CustomCsv extends Csv
      {
          public function parseWithCustomRules($content)
          {
              $data = $this->parse($content);
              // Add custom logic (e.g., data transformation)
              return $data;
          }
      }
      
  2. Event Listeners:

    • Attach listeners to Symfony events (e.g., kernel.request) to log or modify CSV operations:
      // src/EventListener/CsvListener.php
      public function onKernelRequest(GetResponseEvent $event)
      {
          if ($event->isMasterRequest() && $event->getRequest()->query->has('parse_csv')) {
              $csv = new Csv();
              $data = $csv->parse(file_get_contents('temp.csv'));
              // Log or process $data...
          }
      }
      
  3. Integration with Doctrine:

    • Use parsed CSV data to bulk-insert records:
      $entityManager = $this->getDoctrine()->getManager();
      foreach ($csvData as $row) {
          $entity = new YourEntity();
          $entity->setField($row['column']);
          $entityManager->persist($entity);
      }
      $entityManager->flush();
      

Performance Tips

  1. Batch Processing:

    • Process CSV data in chunks to avoid memory overload:
      $chunkSize = 1000;
      $stream = fopen('large.csv', 'r');
      $i = 0;
      while (($data = $csv->parseStream($stream, $chunkSize)) !== false) {
          // Process $data chunk
          $i++;
      }
      
  2. Caching:

    • Cache parsed CSV data if reused frequently (e.g., in a service):
      private $cachedData = [];
      
      public function getCachedData($filePath)
      {
          if (!isset($this->cachedData[$filePath])) {
              $csv = new Csv();
              $this->cachedData[$filePath] = $csv->parse(file_get_contents($filePath));
          }
          return $this->cachedData[$filePath];
      }
      
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.
terminal42/code-quality-tools
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