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

Doctrine Orm Bridge Laravel Package

bengor-file/doctrine-orm-bridge

Doctrine ORM bridge for BenGorFile/File. Provides adapters/mappings to persist File domain objects with Doctrine ORM in PHP (>=5.5). Install via Composer; fully tested with PHPSpec. Documentation lives in the main File library docs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require bengor-file/doctrine-orm-bridge
    

    Ensure your Laravel project uses Doctrine ORM (e.g., via doctrine/orm or a Laravel Doctrine integration package like laravel-doctrine/orm).

  2. Register the Bridge Add the bridge to your Doctrine ORM configuration (e.g., in config/doctrine.php or your Doctrine setup):

    use BenGorFile\DoctrineORMBridge\FileType;
    
    $types['file'] = FileType::class;
    
  3. First Use Case: Storing a File Entity Define an entity with a File field (from the BenGorFile/File library) and map it to Doctrine:

    use Doctrine\ORM\Mapping as ORM;
    use BenGorFile\File;
    
    /**
     * @ORM\Entity
     */
    class UploadedFile
    {
        /**
         * @ORM\Column(type="file")
         */
        private $file;
    
        public function setFile(File $file): void
        {
            $this->file = $file;
        }
    
        public function getFile(): ?File
        {
            return $this->file;
        }
    }
    
  4. Persist a File

    use BenGorFile\File;
    use Doctrine\ORM\EntityManagerInterface;
    
    $file = new File('path/to/local/file.pdf');
    $upload = new UploadedFile();
    $upload->setFile($file);
    
    $entityManager->persist($upload);
    $entityManager->flush();
    

Implementation Patterns

Workflows

1. File Upload and Storage

  • Laravel Controller Integration:
    use BenGorFile\File;
    use Doctrine\ORM\EntityManagerInterface;
    
    public function upload(Request $request, EntityManagerInterface $em)
    {
        $file = new File($request->file('document')->path());
        $upload = new UploadedFile();
        $upload->setFile($file);
    
        $em->persist($upload);
        $em->flush();
    
        return redirect()->back()->with('success', 'File uploaded!');
    }
    

2. Querying Files

  • Use Doctrine’s DQL to filter or retrieve files:
    $files = $em->createQuery('SELECT u.file FROM App\Entity\UploadedFile u')
                ->getResult();
    
  • Note: The bridge supports basic Doctrine operations like find(), findBy(), and custom queries.

3. File Metadata Handling

  • Access file properties (e.g., name, size, mimeType) via Doctrine:
    $uploadedFile = $em->find(UploadedFile::class, 1);
    $file = $uploadedFile->getFile();
    echo $file->getName(); // "document.pdf"
    

4. File Deletion

  • Soft delete (if configured) or hard delete:
    $uploadedFile = $em->find(UploadedFile::class, 1);
    $em->remove($uploadedFile);
    $em->flush();
    
  • Tip: Override File lifecycle callbacks (e.g., preRemove) to handle cleanup.

Integration Tips

Laravel-Specific Patterns

  1. Service Container Binding Bind the File entity to Doctrine’s type system in a service provider:

    public function boot()
    {
        $this->app->make('doctrine')->getConfiguration()
            ->addCustomStringType('file', FileType::class);
    }
    
  2. Form Request Validation Use Laravel’s validation with Doctrine-ORM-bridge:

    public function rules()
    {
        return [
            'document' => 'required|file|mimes:pdf,docx',
        ];
    }
    
  3. File Storage Backends Configure the underlying BenGorFile/File library to use Laravel’s storage (e.g., S3, local):

    $file = new File();
    $file->setStorage(new \BenGorFile\Storage\Adapter\LocalAdapter(
        storage_path('app/public')
    ));
    

Gotchas and Tips

Pitfalls

  1. Outdated Package

    • Last release was 2018. Test thoroughly in your environment.
    • Mitigation: Fork the repo and update dependencies (e.g., Doctrine ORM compatibility).
  2. Missing Doctrine Events

    • The bridge does not automatically handle Doctrine lifecycle events (e.g., prePersist, preRemove).
    • Fix: Manually bind events to your entity:
      $em->getEventManager()->addEventListener(
          UploadedFile::class,
          new FileLifecycleListener()
      );
      
  3. File Path Handling

    • The bridge assumes File objects are already initialized with a path. Passing uninitialized files may cause errors.
    • Tip: Validate files before persistence:
      if (!$file->getPath()) {
          throw new \RuntimeException('File path not set.');
      }
      
  4. Query Limitations

    • Complex queries (e.g., WHERE file.name LIKE '%pdf%') may fail if the bridge doesn’t support the underlying File methods.
    • Workaround: Use native queries or hydrate results manually.

Debugging

  1. Doctrine Logging Enable SQL logging to debug queries:

    $em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    
  2. File Object Dumping Use var_dump() or dd() to inspect File objects during debugging:

    dd($uploadedFile->getFile()->getMetadata());
    
  3. Event Listener Debugging Add logging to custom listeners:

    public function prePersist(LifecycleEventArgs $args)
    {
        \Log::debug('File prePersist triggered', [
            'file' => $args->getObject()->getFile()->getPath()
        ]);
    }
    

Extension Points

  1. Custom File Types Extend the bridge to support additional file types (e.g., Image):

    class ImageType extends FileType
    {
        public function convertToDatabaseValue($value, AbstractPlatform $platform)
        {
            if ($value instanceof \BenGorFile\Image) {
                return $value->getPath();
            }
            return parent::convertToDatabaseValue($value, $platform);
        }
    }
    
  2. Storage Adapter Integration Override the default storage adapter for cloud storage:

    $file->setStorage(new \BenGorFile\Storage\Adapter\S3Adapter(
        new \Aws\S3\S3Client([...])
    ));
    
  3. Doctrine Events Add custom logic to Doctrine events:

    $em->getEventManager()->addEventListener(
        \Doctrine\ORM\Events::preUpdate,
        function ($event) {
            $file = $event->getObject()->getFile();
            if ($file->isDirty()) {
                // Custom logic (e.g., update checksum)
            }
        }
    );
    

Configuration Quirks

  1. Type Mapping Ensure the file type is registered before entity metadata is loaded:

    $config = $em->getConfiguration();
    $config->addCustomStringType('file', FileType::class);
    
  2. Case Sensitivity Doctrine column types are case-sensitive. Use type="file" (lowercase) in annotations/YAML.

  3. PHP Version The package requires PHP 5.5+, but some features (e.g., return type hints) may need PHP 7.1+ for full compatibility.

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui