You can install Flysystem via Composer.
To use Flysystem, you first have to include the vendor autoload file which you got when you installed Flysystem on your working directory. After that, use the
Filesystem class in the
League\Flysystem namespace and the
Local class in the
League\Flysystem\Adapter namespace. The
Filesystem class allows you to use the main Flysystem package. And the
Local class allows you to use the local adapter. With Flysystem it’s not just the local filesystem that you can work with. It has adapters for any cloud storage service that you can think of. Theres an adapter for Dropbox, FTP, AWS S3, Rackspace and even a Zip archive. So the
Local class allows you to work with files in your local filesystem.
1 2 3 4 5 6
Next, create a new instance of the
Local class and pass in the path to the base path you want to work with. This allows you to create an adapter for a local path in your filesystem. In the example below, it’s the
upload directory located in the root of my working directory. After that, create a new instance of the
Filesystem class and pass in the local adapter as the argument.
1 2 3 4
Once that’s done, you can now use Flysystem to wreack havoc on your local filesystem.
Check if File Exists
To check if a file exists, you can use the
has method and then pass in the path to the file. Remember that this uses the root path that you passed in when you created the local adapter.
1 2 3
Reading files only really makes sense for text files. You can use the
read method for this.
1 2 3
Write to Files
When writing to files, the path doesn’t need to already exist. You can pass in a long path and it will create the individual directories that precedes the actual file.
1 2 3
Copying files can work with any file type and the destination doesn’t need to be the same path where the original file exists.
1 2 3
You can use the
rename method to rename files. This also doubles as a move function because you can assign the same name to the file but have a different path.
1 2 3 4
If you want to delete a file, use the
1 2 3
Listing Contents of a Directory
To list the contents of the root directory, you need to call the
listContents method. This returns an array containing the items in the root directory. Note that this isn’t a recursive function. This means that only the direct children of the root directory is going to be listed.
1 2 3 4 5 6 7 8
Get File Information
You can use any of the functions below to get specific information about the file.
1 2 3 4 5
When performing an operation on the filesystem, be sure to wrap it in a
try..catch block so that you can handle the errors accordingly. In the example below, if
file.txt doesn’t exists in the directory, it would return an error.
1 2 3 4 5 6 7
In this tutorial, you’ve learned how to ease filesystem work with the Flysystem library. You have barely scratch the surface with what’s possible with Flysystem. Be sure to check out their official website to learn more.