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

Storage Blob Flysystem Laravel Package

azure-oss/storage-blob-flysystem

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require azure-oss/storage-blob-flysystem
    

    For Laravel, prefer azure-oss/storage-blob-laravel for seamless integration.

  2. Basic Usage

    use AzureOss\Storage\Blob\BlobServiceClient;
    use League\Flysystem\Filesystem;
    use League\Flysystem\AzureBlob\AzureBlobAdapter;
    
    // Initialize BlobServiceClient
    $blobServiceClient = BlobServiceClient::createFromConnectionString(
        env('AZURE_STORAGE_CONNECTION_STRING')
    );
    
    // Create Flysystem adapter
    $adapter = new AzureBlobAdapter(
        $blobServiceClient->getContainerClient('my-container')
    );
    
    // Instantiate Filesystem
    $filesystem = new Filesystem($adapter);
    
  3. First Use Case: Upload a File

    $filesystem->write('path/to/file.txt', 'Hello Azure!');
    

Where to Look First


Implementation Patterns

Core Workflows

  1. Filesystem Operations Leverage Flysystem’s familiar API for:

    • Uploading/downloading files:
      $filesystem->write('file.txt', file_get_contents('local.txt'));
      $content = $filesystem->read('file.txt');
      
    • Directory handling:
      $filesystem->createDirectory('folder');
      $filesystem->deleteDirectory('folder');
      
  2. Laravel Filesystem Integration Add to config/filesystems.php:

    'disks' => [
        'azure' => [
            'driver' => 'azure-blob',
            'connection' => 'azure',
        ],
        'azure-connection' => [
            'driver' => 'azure-blob',
            'connection_string' => env('AZURE_STORAGE_CONNECTION_STRING'),
            'container' => env('AZURE_CONTAINER_NAME'),
        ],
    ],
    

    Use in code:

    use Illuminate\Support\Facades\Storage;
    Storage::disk('azure')->put('file.txt', 'Content');
    
  3. Metadata and Custom Properties Use BlobServiceClient directly for advanced Azure features:

    $blobClient = $blobServiceClient->getBlobClient('container', 'file.txt');
    $blobClient->setMetadata(['customKey' => 'customValue']);
    
  4. Event Handling Listen for Azure Storage events (e.g., blob uploads) via Azure Event Grid or SDK callbacks:

    $blobServiceClient->getContainerClient('container')
        ->addEventSubscription('event-grid-endpoint', ['eventTypes' => ['Microsoft.Storage.BlobCreated']]);
    

Integration Tips

  • Caching: Use Laravel’s cache to store temporary file paths or metadata.
  • Async Operations: Offload heavy uploads/downloads to queues (e.g., Laravel Queues).
  • Error Handling: Wrap operations in try-catch blocks for AzureStorageException:
    try {
        $filesystem->write('file.txt', 'Content');
    } catch (AzureStorageException $e) {
        Log::error('Azure upload failed: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Connection Strings

    • Issue: Hardcoding connection strings in code.
    • Fix: Use Laravel’s .env or environment variables:
      AZURE_STORAGE_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...
      
  2. Container Existence

    • Issue: Assuming containers exist; AzureBlobAdapter throws exceptions if not.
    • Fix: Create containers programmatically:
      $blobServiceClient->createContainer('my-container');
      
  3. Permission Scopes

    • Issue: Using SAS tokens with insufficient permissions (e.g., missing Write).
    • Fix: Generate SAS tokens with explicit permissions:
      $sasToken = $blobServiceClient->generateSasToken(
          'container',
          ['sp' => 'rw'] // Read + Write
      );
      
  4. Large File Handling

    • Issue: Memory limits for large files (>100MB).
    • Fix: Use chunked uploads:
      $blobClient->uploadFromStream('file.txt', fopen('local.txt', 'r'), [
          'blockSize' => 4 * 1024 * 1024, // 4MB blocks
      ]);
      
  5. Timeouts

    • Issue: Long-running operations timing out.
    • Fix: Adjust SDK timeout settings:
      $blobServiceClient = BlobServiceClient::createFromConnectionString(
          env('AZURE_STORAGE_CONNECTION_STRING'),
          ['timeout' => 30] // 30 seconds
      );
      

Debugging

  • Enable Logging: Set Azure SDK logging level:
    AzureOss\Storage\Common\AzureLogger::setLogLevel(\Monolog\Logger::DEBUG);
    
  • Check SDK Logs: Monitor for AzureStorageException or AzureRequestException in Laravel logs.

Extension Points

  1. Custom Adapters Extend AzureBlobAdapter for custom logic (e.g., auto-prefixing paths):

    class CustomAzureBlobAdapter extends AzureBlobAdapter {
        public function writeStream($path, $resource, array $options) {
            $path = 'custom-prefix/' . $path;
            return parent::writeStream($path, $resource, $options);
        }
    }
    
  2. Event Subscribers Subscribe to Flysystem events for pre/post-actions:

    $filesystem->addListener('preWrite', function ($event) {
        Log::debug('Pre-write event for: ' . $event->getPath());
    });
    
  3. Laravel Service Providers Bind custom adapters in AppServiceProvider:

    $this->app->bind('azure-blob-adapter', function () {
        return new CustomAzureBlobAdapter(
            BlobServiceClient::createFromConnectionString(env('AZURE_STORAGE_CONNECTION_STRING'))
                ->getContainerClient('container')
        );
    });
    

Config Quirks

  • Default Endpoint: The SDK defaults to https://<account>.blob.core.windows.net. Override if using custom endpoints:
    BlobServiceClient::createFromConnectionString(
        env('AZURE_STORAGE_CONNECTION_STRING'),
        ['endpointSuffix' => 'core.windows.net'] // Explicit suffix
    );
    
  • Case Sensitivity: Azure Blob Storage paths are case-sensitive on Linux filesystems. Normalize paths:
    $normalizedPath = strtolower($path);
    
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.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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