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

Darvin File Bundle Laravel Package

darvinstudio/darvin-file-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require darvinstudio/darvin-file-bundle
    

    Enable the bundle in config/bundles.php (Symfony 4+):

    DarvinStudio\DarvinFileBundle\DarvinFileBundle::class => ['all' => true],
    
  2. Configuration Publish the default config:

    php bin/console darvin:file:install
    

    Update config/packages/darvin_file.yaml to define storage paths, allowed extensions, and upload limits.

  3. First Use Case Upload a file via a controller:

    use DarvinStudio\DarvinFileBundle\Service\FileManager;
    
    public function upload(Request $request, FileManager $fileManager)
    {
        $file = $request->files->get('file');
        $result = $fileManager->upload($file, 'user_uploads');
    
        return new JsonResponse($result);
    }
    

    Use the enctype="multipart/form-data" in your form.


Implementation Patterns

Core Workflows

  1. File Uploads

    • Use FileManager service for handling uploads:
      $result = $fileManager->upload($file, 'directory', ['max_size' => '10M']);
      
    • Supports validation (size, type, etc.) via config.
  2. File Retrieval

    • Generate URLs for uploaded files:
      $url = $fileManager->getUrl('filename.ext', 'user_uploads');
      
    • Stream files directly to responses:
      return $fileManager->stream('filename.ext', 'user_uploads');
      
  3. File Deletion

    • Remove files programmatically:
      $fileManager->delete('filename.ext', 'user_uploads');
      
  4. Custom Directories

    • Define dynamic directories in config:
      darvin_file:
          directories:
              user_uploads: '%kernel.project_dir%/public/uploads/users'
              profile_avatars: '%kernel.project_dir%/public/uploads/avatars'
      

Integration Tips

  • Symfony Forms Use DarvinStudio\DarvinFileBundle\Form\Type\FileType for form integration:

    $builder->add('file', FileType::class, [
        'label' => 'Upload File',
        'allowed_types' => ['pdf|jpg|png'],
        'max_size' => '5M',
    ]);
    
  • Event Listeners Subscribe to darvin.file.pre_upload and darvin.file.post_upload events for custom logic:

    // src/EventListener/CustomFileListener.php
    public function onPreUpload(PreUploadEvent $event) {
        if (!$event->isValid()) {
            $event->setError('Custom validation failed.');
        }
    }
    
  • API Responses Return structured responses for uploads:

    return $this->json([
        'success' => true,
        'file' => [
            'name' => $result['filename'],
            'url' => $fileManager->getUrl($result['filename'], 'user_uploads'),
        ],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Outdated Package

    • Last release in 2020 may lack compatibility with newer Symfony/Laravel versions.
    • Test thoroughly with your stack (e.g., Symfony 5.4+ or PHP 8.x).
  2. Config Overrides

    • Default config assumes public/uploads as the base directory. Override carefully to avoid permission issues:
      darvin_file:
          base_directory: '%kernel.project_dir%/var/uploads'
      
  3. File Validation

    • Validation rules (e.g., allowed_types) are case-sensitive by default. Normalize extensions if needed:
      $fileManager->upload($file, 'directory', ['allowed_types' => ['jpg', 'jpeg']]);
      
  4. Symlink Risks

    • Avoid using symlinks in base_directory unless explicitly configured, as the bundle may not handle them gracefully.

Debugging

  • Upload Failures Check darvin.file.pre_upload event errors or log the FileManager output:

    $result = $fileManager->upload($file, 'directory', ['log_errors' => true]);
    
  • Permission Issues Ensure the web server user (e.g., www-data) has write permissions:

    chmod -R 775 %kernel.project_dir%/public/uploads
    chown -R www-data:www-data %kernel.project_dir%/public/uploads
    

Extension Points

  1. Custom Storage Extend DarvinStudio\DarvinFileBundle\Storage\StorageInterface for S3/Cloud storage:

    class CustomStorage implements StorageInterface {
        public function save(File $file, string $directory): string {
            // Implement custom logic (e.g., AWS S3 upload)
        }
    }
    

    Register the service in services.yaml:

    DarvinStudio\DarvinFileBundle\Storage\StorageInterface: '@custom_storage'
    
  2. File Processing Hook into darvin.file.post_upload to process files (e.g., generate thumbnails):

    public function onPostUpload(PostUploadEvent $event) {
        $filePath = $event->getFilePath();
        // Run FFmpeg/Imagick here
    }
    
  3. Dynamic Directories Use a callback in config to generate directory paths dynamically:

    darvin_file:
        directories:
            dynamic_dir: '%kernel.project_dir%/public/uploads/%user_id%'
    

    Then resolve %user_id% via a compiler pass or runtime logic.

Performance Tips

  • Chunked Uploads For large files, implement chunked uploads using the darvin.file.pre_upload event to validate chunks before finalizing.
  • Caching URLs Cache generated URLs (e.g., with Symfony’s HTTP cache) to reduce FileManager calls:
    $url = $cache->get('file_url_' . $filename, function() use ($fileManager) {
        return $fileManager->getUrl($filename, 'directory');
    });
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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