ruk·si

PHP
Flysystem

Updated at 2015-02-05 22:28

Flysystem is an abstraction for local and remote filesystems. I can be used to create cached remote filesystems with uniform interface with the local filesystem. This makes easier to write one code version that works on AWS, Azure, local and Dropbox.

Get composer and run this in the project directory.

composer require league/flysystem

Configuring AWS S3 as a filesystem:

use Aws\S3\S3Client;
use League\Flysystem\Adapter\AwsS3 as Adapter;

$client = S3Client::factory(array(
    'key'    => '[your key]',
    'secret' => '[your secret]',
));

$filesystem = new Filesystem(
    new Adapter($client, 'bucket-name', 'optional-prefix')
);

Reading:

$filesystem->listContents(null, true);
$filesystem->listWith(['mimetype', 'size', 'timestamp']);

Copying files:

$local = new Filesystem(new Adapter('/usr/local/'));
$remote = new Filesystem(
    S3Client::factory(array(
        'key'    => '[your key]',
        'secret' => '[your secret]',
    )),
    'my-bucket'
);

if ($local->has('something.txt')) {
    $contents = $local->read('something.txt');
    $remote->write('data.txt', $contents, ['visibility' : 'public']);
}

Mounting:

$s3 = new League\Flysystem\Filesystem($s3Adapter);
$manager = new League\Flysystem\MountManager(array(
    'remote' => new League\Flysystem\Filesystem($s3Adapter),
));

// Save some data to remote storage
$manager->write('remote://path/to/filename', $data);

Caching:

use League\Flysystem\Adapter\Local as Adapter;
use League\Flysystem\Cache\Memcached as Cache;

$memcached = new Memcached;
$memcached->addServer('localhost', 11211);
$filesystem = new Filesystem(new Adapter(__DIR__.'/path/to/root'), new Cache($memcached, 'storageKey', 300));
// Storage Key and expire time are optional

Sources