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

Attachment Bundle Laravel Package

c33s/attachment-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require c33s/attachment-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        C33s\AttachmentBundle\C33sAttachmentBundle::class => ['all' => true],
    ];
    
  2. Configure Database Run migrations (Propel-specific):

    php app/console propel:model:build
    php app/console propel:migrate
    

    Verify attachment and attachment_object tables exist.

  3. First Use Case Attach a file to a model (e.g., Product):

    use C33s\AttachmentBundle\Model\Attachment;
    
    $product = ProductQuery::create()->findOne(1);
    $attachment = new Attachment();
    $attachment->setFile('path/to/file.pdf');
    $attachment->setObject($product);
    $attachment->save();
    

Implementation Patterns

Core Workflows

  1. Attachments to Models Use Attachment model to link files to any Propel object:

    // Attach multiple files
    $attachments = [];
    foreach ($request->files as $file) {
        $attachment = new Attachment();
        $attachment->setFile($file->getPathname());
        $attachment->setObject($model);
        $attachment->save();
        $attachments[] = $attachment;
    }
    
  2. Retrieving Attachments Fetch attachments for a model:

    $attachments = AttachmentQuery::create()
        ->filterByObject($model)
        ->find();
    
  3. File Management

    • Upload Handling: Use Symfony’s File component to process uploads before saving:
      $file = $request->files->get('file');
      $attachment->setFile($file->getRealPath());
      
    • Storage: Defaults to filesystem; extend for S3/Cloud storage (see Gotchas).
  4. Validation Validate file types/sizes via Propel behavior or custom logic:

    if ($file->getClientOriginalExtension() !== 'pdf') {
        throw new \RuntimeException('Only PDF allowed.');
    }
    
  5. Integration with Forms Use Symfony’s FileType field in forms:

    $builder->add('attachments', CollectionType::class, [
        'entry_type' => new AttachmentType(),
        'allow_add' => true,
        'allow_delete' => true,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Propel Dependency

    • Bundle is Propel-only; avoid if using Doctrine. For Doctrine, consider VichUploaderBundle.
    • If migrating from Propel, ensure Attachment and AttachmentObject tables are manually created.
  2. File Storage Quirks

    • Default storage uses Attachment::getFilePath() (e.g., uploads/attachments/). Override in config:
      # config.yml
      c33s_attachment:
          storage_path: '%kernel.project_dir%/public/uploads/custom_path'
      
    • Permissions: Ensure storage_path is writable by the web server user.
  3. Memory Limits Large files may hit PHP’s upload_max_filesize or memory_limit. Adjust in php.ini or use chunked uploads.

  4. Deletion Handling

    • Files are not auto-deleted when attachments are removed. Implement a listener:
      // src/EventListener/AttachmentListener.php
      public function postRemove(Attachment $attachment)
      {
          if (file_exists($attachment->getFilePath())) {
              unlink($attachment->getFilePath());
          }
      }
      
    • Register in services.yml:
      services:
          app.attachment_listener:
              class: App\EventListener\AttachmentListener
              tags:
                  - { name: kernel.event_listener, event: attachment.post_remove, method: postRemove }
      
  5. Symfony 4+ Compatibility

    • Bundle targets Symfony 2.x. For Symfony 4/5, test thoroughly or fork the package. Key changes:
      • Replace app/console commands with bin/console.
      • Update autowiring/config for newer Symfony versions.

Debugging Tips

  1. Check Database Verify attachment_object table links are correct:

    SELECT * FROM attachment_object WHERE object_id = [MODEL_ID];
    
  2. File Paths Log paths to confirm files are saved:

    \Log::debug('Attachment path:', [$attachment->getFilePath()]);
    
  3. Event Dispatching Override events for custom logic (e.g., attachment.pre_save):

    $dispatcher->addListener('attachment.pre_save', function (AttachmentEvent $event) {
        $event->getAttachment()->setCustomField('processed', true);
    });
    

Extension Points

  1. Custom Storage Extend C33s\AttachmentBundle\Model\Attachment to support S3:

    use Aws\S3\S3Client;
    
    class CustomAttachment extends Attachment
    {
        public function getFilePath()
        {
            $s3 = new S3Client([...]);
            return $s3->getObjectUri('bucket', $this->getFileName());
        }
    }
    
  2. Validation Rules Add Propel behaviors for file validation:

    # schema.xml
    <behavior name="attachment_validation">
        <parameter name="allowed_extensions" value="pdf,jpg,png"/>
        <parameter name="max_size" value="10M"/>
    </behavior>
    
  3. API Endpoints Create a controller to serve attachments:

    public function serveAttachment(Attachment $attachment, Request $request)
    {
        return new BinaryFileResponse($attachment->getFilePath());
    }
    

    Route:

    # routing.yml
    attachment_download:
        path:     /attachment/{id}
        defaults: { _controller: App\Controller\AttachmentController::serveAttachment }
    
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