Search code examples
phplaravellaravel-storage

Custom filesystem provider to service multiple disks


I have created custom filesystem service provider for setup my google cloud storage. I have multiple buckets so I created multiple disks in filesystems.php. But since all of these buckets are using similar settings I want to use single service provider. Can we achieve that?

ServicePrivider boot()

Storage::extend('gcs_images_1', function ($app, $config) {
    $client = new StorageClient([
        'projectId' => $config['project_id'],
        'keyFilePath' => storage_path($config['key_file'])
    ]);

    $bucket = $client->bucket($config['bucket']);

    $pathPrefix = array_get($config, 'path_prefix');

    $storageApiUri = array_get($config, 'storage_api_uri');

    $adapter = new GoogleStorageAdapter($client, $bucket, $pathPrefix, $storageApiUri);

    return new Filesystem($adapter);
});

config/filesystems.php

'gcs_images_1' => [
            'driver' => 'gcs_images_1',
            'project_id' => env('GOOGLE_CLOUD_PROJECT_ID'),
            'key_file' => env('GOOGLE_CLOUD_KEY_FILE'),
            'bucket' => 'img',
            'path_prefix' => env('GOOGLE_CLOUD_STORAGE_PATH_PREFIX', null),
            'storage_api_uri' => env('GOOGLE_CLOUD_STORAGE_API_URI', null)
        ],
        'gcs_docs_1' => [
            'driver' => 'gcs_docs_1',
            'project_id' => env('GOOGLE_CLOUD_PROJECT_ID'),
            'key_file' => env('GOOGLE_CLOUD_KEY_FILE'),
            'bucket' => 'doc',
            'path_prefix' => env('GOOGLE_CLOUD_STORAGE_PATH_PREFIX', null),
            'storage_api_uri' => env('GOOGLE_CLOUD_STORAGE_API_URI', null)
        ],

Solution

  • So after all solution was simple. Returning array of Filesystem instances

            $fileSystems = array();
            foreach ($this->gcsDisks as $disk) {
                $fileSystems[] = $this->getFileSystem($disk);
            }
            return $fileSystems;
    

    But still more clear way to do this is welcome as a answer