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 Bundle Laravel Package

bengor-file/file-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bengor-file/file-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        BenGorFile\FileBundle\BenGorFileBundle::class => ['all' => true],
    ];
    
  2. Configuration: Publish the default config:

    php bin/console ben-gor-file:install
    

    Or manually configure in config/packages/ben_gor_file.yaml:

    ben_gor_file:
        storage: '%kernel.project_dir%/var/files'
        allowed_extensions: ['jpg', 'png', 'pdf']
        max_file_size: 10M
    
  3. First Use Case: Upload a file via a controller:

    use BenGorFile\FileBundle\Service\FileUploader;
    
    public function upload(Request $request, FileUploader $uploader)
    {
        $file = $request->file('file');
        $path = $uploader->upload($file, 'uploads');
    
        return new JsonResponse(['path' => $path]);
    }
    

Implementation Patterns

Core Workflows

  1. File Uploads:

    • Use FileUploader service for handling uploads with validation:
      $uploader->upload($file, 'custom/directory', ['allowed_extensions' => ['jpg']]);
      
    • Supports chunked uploads for large files via ChunkedFileUploader.
  2. File Management:

    • Deletion:
      $this->fileManager->delete($filePath);
      
    • Renaming:
      $this->fileManager->rename($oldPath, $newPath);
      
    • Metadata:
      $metadata = $this->fileMetadata->getMetadata($filePath);
      
  3. Integration with Forms:

    • Use FileType form field for Symfony forms:
      use BenGorFile\FileBundle\Form\Type\FileType;
      
      $builder->add('document', FileType::class, [
          'label' => 'Upload Document',
          'allowed_extensions' => ['pdf', 'docx'],
      ]);
      
  4. Storage Adapters:

    • Switch storage backends (local, S3, etc.) via configuration:
      ben_gor_file:
          storage_adapter: 'aws_s3'
          aws_s3:
              bucket: 'my-bucket'
              region: 'us-east-1'
      
  5. Event Listeners:

    • Listen to file upload events:
      public function onFileUpload(FileUploadEvent $event)
      {
          if ($event->isValid()) {
              // Process file
          }
      }
      
    • Register in services.yaml:
      services:
          App\EventListener\FileUploadListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'file.upload', method: 'onFileUpload' }
      

Gotchas and Tips

Common Pitfalls

  1. Configuration Overrides:

    • Ensure ben_gor_file.yaml is merged correctly. Use !imports or parameters to override defaults without losing other settings.
  2. File Validation:

    • The bundle validates extensions and sizes before saving. Customize validation rules in config/packages/ben_gor_file.yaml:
      ben_gor_file:
          validation:
              allowed_extensions: ['jpg', 'png', 'gif']
              max_file_size: 5M
              forbidden_patterns: ['/malicious\.php$/']
      
  3. Permissions:

    • If using local storage, ensure the storage directory is writable:
      chmod -R 775 %kernel.project_dir%/var/files
      
  4. Chunked Uploads:

    • For large files (>100MB), use ChunkedFileUploader but ensure:
      • The session is configured to handle large uploads (session.save_path).
      • The temp directory has enough space.
  5. Symfony 5+ Compatibility:

    • The bundle was last updated in 2018. Test thoroughly with Symfony 5/6:
      • Override FileUploader service if autowiring fails:
        services:
            BenGorFile\FileBundle\Service\FileUploader:
                arguments:
                    $container: '@service_container'
        

Debugging Tips

  1. Log Upload Events: Enable debug mode and check logs for file.upload events:

    monolog:
        handlers:
            main:
                level: debug
    
  2. Validate File Paths: Use absolute paths for storage. Relative paths may break in production.

  3. Check Storage Adapter: If files disappear, verify the storage_adapter is correctly configured and the underlying service (e.g., AWS SDK) is initialized.

Extension Points

  1. Custom Storage Adapters: Implement BenGorFile\FileBundle\Storage\StorageInterface:

    class CustomStorage implements StorageInterface {
        public function save($file, $path) { /* ... */ }
        public function delete($path) { /* ... */ }
    }
    

    Register in services.yaml:

    ben_gor_file.storage_adapter: '@app.custom_storage'
    
  2. Custom Validators: Extend BenGorFile\FileBundle\Validator\Constraints\File:

    class CustomFileValidator extends FileValidator {
        protected function validateCustomRule($value, Constraint $constraint) {
            // Custom logic
        }
    }
    
  3. Twig Extensions: Add file-related Twig functions:

    // src/Twig/FileExtension.php
    class FileExtension extends \Twig\Extension\AbstractExtension {
        public function getFunctions() {
            return [
                new \Twig\TwigFunction('file_url', [$this, 'getFileUrl']),
            ];
        }
    }
    
  4. Console Commands: Create custom commands for bulk operations:

    use BenGorFile\FileBundle\Service\FileManager;
    
    class CleanupCommand extends Command {
        protected function execute(InputInterface $input, OutputInterface $output, FileManager $manager) {
            $manager->deleteOldFiles('logs', '-1 month');
        }
    }
    

Performance Tips

  1. Cache Metadata: Cache file metadata (e.g., size, mime type) to avoid repeated calls to FileMetadata:

    $this->cache->remember("file_metadata_{$path}", 3600, function() use ($path) {
        return $this->fileMetadata->getMetadata($path);
    });
    
  2. Async Processing: Use Symfony Messenger to process uploads asynchronously:

    $message = new ProcessFileMessage($filePath);
    $this->messageBus->dispatch($message);
    
  3. Batch Operations: For bulk uploads, use FileUploader::uploadMultiple() and process in chunks to avoid memory issues.


```markdown
## Maintenance Notes
- **Deprecation**: The package is outdated (last release 2018). Fork and update for Symfony 5/6 if critical.
- **Testing**: Run PHPSpec tests locally to understand expected behavior:
  ```bash
  composer require phpspec/phpspec --dev
  vendor/bin/phpspec run
  • Backup: Always back up the storage directory before running cleanup commands.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle