sajad torkamani

In a nutshell

Flysystem is a PHP library that provides a single API for working with many different types of file systems (e.g., Local, AWS S3, Google Cloud Storage, Azure Blob Storage memory, etc). The benefits are:

  1. Avoid vendor lock-in: Switch between storage providers without changing your application’s code.
  2. Easier time working with files. The Flysystem API provides expressive methods like $flysystem->write($path, $contents) that make working with file systems easier.

You start by:

  • Installing the core library (e.g., composer require league/flysystem:^3.0)
  • Installing an adapter (e.g., composer require league/flysystem-aws-s3-v3:^3.0)

Then you can work with the filesystem like so:

// SETUP
$adapter = new League\Flysystem\Local\LocalFilesystemAdapter($rootPath);
$filesystem = new League\Flysystem\Filesystem($adapter);

// USAGE
$filesystem->write($path, $contents);

In the above example, we used the Local adapter, but using an alternative adapter like AWS S3 looks very similar:

/** @var Aws\S3\S3ClientInterface $client */
$client = new Aws\S3\S3Client($options);

// The internal adapter
$adapter = new League\Flysystem\AwsS3V3\AwsS3V3Adapter(
    // S3Client
    $client,
    // Bucket name
    'bucket-name'
);

// The FilesystemOperator
$filesystem = new League\Flysystem\Filesystem($adapter);

Symfony integration

Install package:

composer require league/flysystem-bundle

Configure as needed:

# config/packages/flysystem.yaml

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

Use:

use League\Flysystem\FilesystemOperator;

class MyService
{
    private $storage;
    
    // The variable name $defaultStorage matters: it needs to be the camelized version
    // of the name of your storage. 
    public function __construct(FilesystemOperator $defaultStorage)
    {
        $this->storage = $defaultStorage;
    }
    
    // ...
}

Other notes

Sources