Flysystem reference
28 November 2022 (Updated 10 March 2024)
On this page
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:
- Avoid vendor lock-in: Switch between storage providers without changing your application’s code.
- 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
- There’s a
league/flysystem-bundle
Symfony bundle that helps integrate the Flysystem library into Symfony applications. - Using memory storage in tests
- Using read only to disallow any write operations
Sources
Tagged:
PHP tooling
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment