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

Remote Bundle Laravel Package

clickandmortar/remote-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**: Add the bundle via Composer:
   ```bash
   composer require clickandmortar/remote-bundle
  1. Enable Bundle: Register in config/bundles.php:
    ClickAndMortar\RemoteBundle\ClickAndMortarRemoteBundle::class => ['all' => true],
    
  2. First Use Case: Test a simple file download via CLI:
    php bin/console candm:remote:get ftp user@example.com /remote/path/file.txt ./local/directory
    
    (Replace ftp with sftp, scp, or other supported types from the bundle.)

Key Configuration

  • Supported Protocols: Check config/packages/clickandmortar_remote.yaml (if auto-generated) or the bundle’s docs for available transfer types (e.g., ftp, sftp, scp).
  • Credentials: Store sensitive data (passwords, servers) in .env or a secure config file. Example:
    REMOTE_SERVER=ftp.example.com
    REMOTE_USER=admin
    REMOTE_PASSWORD=secure123
    

Implementation Patterns

Workflows

1. Scheduled Transfers

  • Use Case: Automate nightly backups or syncs.
  • Pattern: Schedule CLI commands via Laravel’s schedule:run or a cron job:
    * * * * * cd /path/to/project && php artisan schedule:run >> /dev/null 2>&1
    
  • Example Command:
    php bin/console candm:remote:get ftp {REMOTE_USER} /backups/*.sql ./storage/backups --schedule
    

2. Dynamic File Handling

  • Use Case: Process files from a remote server dynamically (e.g., CSV imports).
  • Pattern: Use Laravel’s Storage facade to interact with downloaded files:
    use Illuminate\Support\Facades\Storage;
    
    // After download, process the file
    $filePath = './local/directory/received_file.csv';
    $contents = Storage::disk('local')->get($filePath);
    // Parse/process $contents...
    

3. Event-Driven Transfers

  • Use Case: Trigger transfers on model events (e.g., upload user avatars when a User is created).
  • Pattern: Bind to Laravel events in EventServiceProvider:
    public function boot()
    {
        User::created(function ($user) {
            $this->uploadAvatar($user->avatar_path);
        });
    }
    
  • Helper Method:
    protected function uploadAvatar($localPath)
    {
        $command = "candm:remote:put sftp {$this->remoteUser} {$localPath} /remote/avatars/{$user->id}.jpg";
        exec($command);
    }
    

4. Batch Processing

  • Use Case: Download/upload multiple files in a loop.
  • Pattern: Use Laravel’s collect() to iterate over files:
    $remoteFiles = ['file1.txt', 'file2.txt'];
    collect($remoteFiles)->each(function ($file) {
        Artisan::call('candm:remote:get', [
            'type' => 'sftp',
            'user' => 'admin',
            'distantFilePaths' => "/remote/{$file}",
            'localDirectory' => './downloads',
        ]);
    });
    

Integration Tips

  • Logging: Wrap commands in a try-catch to log failures:
    try {
        Artisan::call('candm:remote:get', [...]);
    } catch (\Exception $e) {
        Log::error("Remote transfer failed: {$e->getMessage()}");
    }
    
  • Configuration: Override default settings in config/packages/clickandmortar_remote.yaml:
    click_and_mortar_remote:
        default_timeout: 30  # Override timeout in seconds
        retries: 3           # Add retry logic for failed transfers
    
  • Testing: Mock the bundle’s RemoteService in PHPUnit:
    $this->partialMock(ClickAndMortar\RemoteBundle\Service\RemoteService::class, ['download']);
    

Gotchas and Tips

Pitfalls

  1. Protocol Limitations:

    • Issue: Not all protocols support the same features (e.g., scp lacks directory listing).
    • Fix: Verify supported methods in the bundle’s source (src/Service/RemoteService.php). Fall back to sftp for complex operations.
  2. Permission Errors:

    • Issue: Remote server rejects connections due to incorrect credentials or permissions.
    • Debug: Enable verbose output in commands:
      php bin/console candm:remote:get -v ftp user@example.com /file.txt ./local
      
    • Fix: Ensure the remote user has read/write access to the target paths.
  3. File Path Handling:

    • Issue: Relative paths may break if working directories differ between local/remote.
    • Fix: Use absolute paths or resolve them dynamically:
      $localPath = realpath('./relative/path/file.txt');
      
  4. Command Line Escaping:

    • Issue: Spaces or special characters in file paths cause CLI parsing errors.
    • Fix: Quote paths or use -- to separate options:
      php bin/console candm:remote:get ftp user@example.com "/path/with spaces/file.txt" "./local/dir"
      

Debugging

  • Check Logs: Enable Laravel’s debug mode (APP_DEBUG=true) and check storage/logs/laravel.log.
  • Dry Runs: Test with a dummy file first to validate paths/permissions:
    touch test.txt && php bin/console candm:remote:put ftp user@example.com test.txt /remote/test.txt
    
  • Timeouts: Increase the timeout for slow connections:
    php bin/console candm:remote:get -t 60 ftp user@example.com /file.txt ./local
    

Extension Points

  1. Custom Protocols:

    • How: Extend ClickAndMortar\RemoteBundle\Service\RemoteService and register a new adapter in the bundle’s DI container.
    • Example: Add AWS S3 support by implementing RemoteAdapterInterface.
  2. Pre/Post-Transfer Hooks:

    • How: Publish the bundle’s config and bind events to file operations:
      // In a service provider
      $this->app->booted(function () {
          event(new RemoteFileDownloaded('file.txt', './local'));
      });
      
  3. Progress Tracking:

    • How: Override the bundle’s command classes to add progress bars (e.g., using Symfony’s ProgressBar):
      use Symfony\Component\Console\Style\SymfonyStyle;
      
      class CustomDownloadCommand extends AbstractCommand {
          protected function execute(InputInterface $input, OutputInterface $output) {
              $style = new SymfonyStyle($input, $output);
              $style->progressStart(100);
              // Simulate progress...
              $style->progressAdvance(50);
              $style->progressFinish();
          }
      }
      

Configuration Quirks

  • Default Values: The bundle may use hardcoded defaults (e.g., timeout = 10s). Override in config/packages/clickandmortar_remote.yaml:
    click_and_mortar_remote:
        timeout: 60  # Override globally
    
  • Environment Variables: Prefer .env for sensitive data:
    REMOTE_BUNDLE_TIMEOUT=60
    
    Then reference in config:
    timeout: '%env(int:REMOTE_BUNDLE_TIMEOUT, 10)%'
    

Performance Tips

  • Batch Downloads: Use wildcards to fetch multiple files in one command:
    php bin/console candm:remote:get ftp user@example.com /files/*.jpg ./local
    
  • Compression: For large transfers, compress files locally before uploading:
    tar -czf backup.tar.gz /local/files && php bin/console candm:remote:put ftp user@example.com backup.tar.gz /remote/backup.tar.gz
    
  • Parallel Transfers: Use Laravel queues to process multiple transfers concurrently:
    RemoteTransferJob::dispatch('ftp', 'user@example.com', '/file1.txt', './local')->onQueue('remote-transfers');
    
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.
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views
spatie/ignition-contracts
earls/stork-command-queue-bundle