phpflysystem

Flysystem v3: issue using Local adapter


I'm a new user of Flysystem.

To get started I'm trying to write files within an existing php app using the Local adapter.

I'm setting up the adapter / file system using this approach:

$adapter = new LocalFilesystemAdapter('/');
$filesystem = new Filesystem($adapter);

When I come to write out the files I'm submitting this instruction:

filesystem->write('/var/www/html/public_html/files/'.$file_name, $file_content);

However this generates no errors, but also no saved file.

I traced the execution of the write, and it turns out when it comes to the @file_put_contents step (line 123 of LocalFileSystemAdapter.php) the path that is supplied is var/www/html/public_html/files/'.$file_name (i.e. what was supplied, but missing the opening /).

The file_put_contents instruction is therefore writing the output to a relative path, rather than to the path provided / required.

How do I change things so that Flysystem writes to the path required?

Thanks in advance for whatever guidance you can offer. Attempts to write files fail because the write-path is incorrect.


Solution

  • tl;dr you're not supposed to provide full path when writing, you're using Flysystem incorrectly.


    Flysystem is a filesystem abstraction layer (it abstracts away details of "how" and "where" to store data.) To have proper separation of concerns in your code, you want your code NOT to know where the data is exactly stored (what's the location, what's the medium etc… should you ever want to switch to a different storage.)

    When writing a file, your code should be oblivious to the adapter you're trying to use. If you say, one day, decide to switch to the cloud, in theory switching will be as easy as changing the filesystem's adapter somewhere in the configuration – you won't have to make any changes to your code.

    By design, Flysystem operates on file keys (the first parameter of the write method.) To write a file you're supposed to:

    // configure where to store your data
    $adapter = new LocalFilesystemAdapter('/var/www/html/public_html/files');
    
    // instantiate the abstraction layer
    $filesystem = new Filesystem($adapter);
    
    // store the data using the abstraction
    $filesystem->write('test.txt', 'file contents');
    

    This will create a file called test.txt in the /var/www/html/public_html/files directory.

    Your file keys can also contain "directories":

    $filesystem->write('textfiles/test.txt', 'file contents');
    

    This would create a file called test.txt in the /var/www/html/public_html/files/textfiles directory. Try it!

    If you decide to use, i.e. AwsS3V3Adapter, Flysystem would create textfiles/test.txt file in your AWS bucket.

    To read the created file, you have to use the same file key used to write the file:

    echo $filesystem->read('file.txt');
    

    Extra tip: you can have multiple sources defined, i.e.


    References: