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

File Handler Bundle Laravel Package

betamfd/file-handler-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require betamfd/file-handler-bundle
    

    Add to config/bundles.php (Symfony):

    return [
        // ...
        BetaMFD\FileHandlerBundle\BetaMFDFileHandlerBundle::class => ['all' => true],
    ];
    
  2. First Use Case Upload a file via a Symfony form:

    // src/Form/FileUploadType.php
    use BetaMFD\FileHandlerBundle\Form\FileType;
    
    class FileUploadType extends AbstractType {
        public function buildForm(FormBuilderInterface $builder, array $options) {
            $builder->add('file', FileType::class, [
                'label' => 'Upload File',
                'mime_types' => ['image/jpeg', 'image/png'],
                'max_size' => '10M',
            ]);
        }
    }
    
  3. Handling Uploads

    // src/Controller/FileUploadController.php
    use BetaMFD\FileHandlerBundle\Service\FileHandler;
    
    class FileUploadController extends AbstractController {
        public function upload(Request $request, FileHandler $fileHandler) {
            $form = $this->createForm(FileUploadType::class);
            $form->handleRequest($request);
    
            if ($form->isSubmitted() && $form->isValid()) {
                $file = $form->get('file')->getData();
                $path = $fileHandler->store($file, 'uploads');
                // $path now contains the stored file location
            }
        }
    }
    

Implementation Patterns

Core Workflows

  1. File Validation & Processing

    // Validate and process with custom rules
    $fileHandler->validate($file, [
        'mime_types' => ['application/pdf'],
        'max_size' => '5M',
        'extensions' => ['pdf'],
        'custom' => function ($file) {
            return $file->getClientOriginalExtension() === 'pdf';
        }
    ]);
    
  2. Storage Integration

    • Local Storage (Default)
      $path = $fileHandler->store($file, 'custom_directory');
      
    • Cloud Storage (AWS S3) Configure in config/packages/betamfd_file_handler.yaml:
      betamfd_file_handler:
          storage:
              default: 'local'
              disks:
                  s3:
                      driver: 's3'
                      key: '%env(AWS_ACCESS_KEY_ID)%'
                      secret: '%env(AWS_SECRET_ACCESS_KEY)%'
                      bucket: 'my-bucket'
      
      Use in code:
      $path = $fileHandler->store($file, 'uploads', 's3');
      
  3. File Metadata & Manipulation

    // Get metadata
    $metadata = $fileHandler->getMetadata($file);
    
    // Resize images (if ImageMagick is installed)
    $resizedPath = $fileHandler->resize($file, 800, 600);
    
  4. Batch Processing

    $files = $request->files->all();
    foreach ($files['documents'] as $file) {
        $fileHandler->store($file, 'documents');
    }
    

Integration Tips

  1. Symfony Events Listen for file upload events:

    // src/EventListener/FileUploadListener.php
    use BetaMFD\FileHandlerBundle\Event\FileUploadEvent;
    
    class FileUploadListener {
        public function onFileUpload(FileUploadEvent $event) {
            if ($event->getFile()->getClientOriginalExtension() === 'pdf') {
                $event->setPath('pdfs/' . $event->getPath());
            }
        }
    }
    

    Register in services.yaml:

    services:
        App\EventListener\FileUploadListener:
            tags:
                - { name: kernel.event_listener, event: betamfd.file_upload, method: onFileUpload }
    
  2. Custom Storage Adapters Extend BetaMFD\FileHandlerBundle\Storage\StorageInterface:

    class CustomStorage implements StorageInterface {
        public function store(File $file, string $directory): string {
            // Custom logic
        }
        // Implement other methods...
    }
    

    Register in config:

    betamfd_file_handler:
        storage:
            disks:
                custom:
                    driver: 'custom'
                    adapter: App\Storage\CustomStorage
    
  3. API File Handling

    // For API responses
    $filePath = $fileHandler->store($file, 'exports');
    return $this->file($filePath, 'report.pdf', [
        'Content-Type' => 'application/pdf',
    ]);
    

Gotchas and Tips

Common Pitfalls

  1. File Size Limits

    • Ensure post_max_size and upload_max_filesize in php.ini exceed your max_size config.
    • Default Symfony limits may override bundle settings. Check config/packages/framework.yaml:
      framework:
          http_method_override: true
          form: true
          csrf_protection: true
          # Ensure these are not stricter than your bundle config
      
  2. Mime Type Validation

    • Some servers misreport mime types (e.g., image/jpeg vs jpeg). Use extensions fallback:
      betamfd_file_handler:
          validation:
              mime_types: ['image/jpeg']
              extensions: ['jpg', 'jpeg']  # Fallback
      
  3. Race Conditions in Storage

    • Use unique filenames to avoid overwrites:
      $path = $fileHandler->store($file, 'uploads', null, true); // $unique = true
      
  4. Cloud Storage Timeouts

    • For large files, increase PHP timeout:
      set_time_limit(300); // 5 minutes
      $fileHandler->store($file, 'large_files');
      

Debugging Tips

  1. Enable Verbose Logging

    betamfd_file_handler:
        debug: true
    

    Check logs at var/log/dev.log for detailed storage operations.

  2. Validate File Paths

    • Use file_exists() to verify stored files:
      if (!file_exists($path)) {
          throw new \RuntimeException('File not stored correctly.');
      }
      
  3. Check Storage Permissions

    • Ensure directories are writable:
      chmod -R 775 var/storage
      

Extension Points

  1. Custom File Naming Override default naming strategy:

    $fileHandler->setNamingStrategy(function (File $file) {
        return 'custom_' . time() . '_' . $file->getClientOriginalName();
    });
    
  2. Post-Processing Hooks Use events to add logic after storage:

    // src/EventSubscriber/FileUploadSubscriber.php
    class FileUploadSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                'betamfd.file_upload.post_store' => 'onPostStore',
            ];
        }
    
        public function onPostStore(FileUploadEvent $event) {
            // Example: Generate a thumbnail
            $fileHandler = $event->getFileHandler();
            $fileHandler->resize($event->getFile(), 200, 200);
        }
    }
    
  3. Fallback Storage Configure fallback disks in betamfd_file_handler.yaml:

    betamfd_file_handler:
        storage:
            disks:
                primary:
                    driver: 's3'
                    fallback: 'local'  // Falls back to local if S3 fails
    
  4. Symfony Messenger Integration Dispatch file processing as async jobs:

    use BetaMFD\FileHandlerBundle\Message\ProcessFileMessage;
    
    $this->messageBus->dispatch(new ProcessFileMessage($file, 'uploads'));
    

    Configure in config/packages/messenger.yaml:

    framework:
        messenger:
            transports:
                async: '%env(MESSENGER_TRANSPORT_DSN)%'
            routing:
                'BetaMFD\FileHandlerBundle\Message\ProcessFileMessage': async
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware