Search code examples
phpsymfonydependency-injectionflysystem

How get specific file storage service in flysystem component in symfony


I'm just wondering how to get specified filestorage instance in flysystem bundle. For example if I have such configuration:

flysystem:
    storages:
        first.storage:
            adapter: 'local'
            options:
                directory: '%kernel.project_dir%/var/storage/storage/first'
        second.storage:
            adapter: 'local'
            options:
                directory: '%kernel.project_dir%/var/storage/default/second'

I want to grab it depending for example on some parameter in factory. Something like that:

$fileSystemStorage = (new FileSystemFactory()->getStorage('second');

and here is my factory:

class FileSystemFactory
{
    public function getStorage(string $storage): FilesystemOperator
    {
        switch ($storage) {
            case 'first':
                break;
            case 'second':
                break;
        }
    }
}

I just don't know how manually to define which options I want to grab from flysystem.yaml.

In documentation it says that I can inject it something like that (name camelcase from configuration): https://github.com/thephpleague/flysystem-bundle

public function __construct(FilesystemOperator $firstStorage)
{
    $this->storage = $firstStorage;
}

But in my case I want manually define it depending on parameter. Of course I can create two classes which have 2 different injections ($firstStorage and $secondStorage), and than return objects from those classes, but maybe there is some more simple way ?


Solution

  • UPDATED!!!

    I've got very similiar problem, and i solved it by using ContainerInterface and service alias (flysystem services aren't public):

    // config/services.yaml
    services:
    // ...
        // we need this for every storage, 
        // flysystems services aren't public and we can solve this using aliases
        first.storage.alias:
            alias: 'first.storage'
            public: true
    
    <?php
    
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class FileSystemFactory
    {
        private $container;
    
        public function __construct(ContainerInterface $container)
        {
            $this->container = $container;
        }
    
        public function getStorage(string $storage)
        {
            $storageContainer = $this->container->get($storage); // ex. first.storage.alias
    
            switch ($storageContainer) {
                case 'first':
                    break;
                case 'second':
                    break;
            }
        }
    }