Edit on GitHub
Jump to docs navigation

Extending / Filesystem Layer / Working with files

Note: You are currently reading the documentation for Bolt 3.7. Looking for the documentation for Bolt 5.2 instead?

Each file in the filesystem is an instance of an \Bolt\Filesystem\Handler\FileInterface object.

Getting a file object

    /** @var \Bolt\Filesystem\Handler\FileInterface $file */
    $file = $filesystem->getFile($path);

Where:

Variable Type Description
$path string Relative path to the file

Checking if a file exists

    /** @var bool $exists */
    $exists = $file->exists($path);
Variable Type Description
$path string The path to the file

Getting a file's contents

Read the contents of a file into a variable.

    $data = $file->read($path);

Where:

Variable Type Description
$path string Relative path to the file

Create & updating files

The FilesystemInterface gives two ways to persist data to a file on a filesystem, ->write() will create a file, and ->put() will persist the data to an existing file, or a new file if the requested target doesn' exist.

    // Create a file or update if exists
    $filesystem->put($path, $contents, $config = []);

    // Write a new file.
    $filesystem->write($path, $contents, $config = []);

Where:

Variable Type Description
$path string The target file
$contents mixed Data to be written to the target file
$config array Optional configuration array

Note: The write() method will throw a `\Bolt\Filesystem\Exception\FileExistsException` if you attempt to write to an existing file, use put() in that circumstance.

Copy Files

Copies a file and its contents to another.

    $filesystem->copy($origin, $target, $override = null)

Where:

Variable Type Description
$origin string The origin file
$target string The target file
override bool/null Whether to override an existing file
true = always override the target
false = never override the target
null = only override the target if the source is newer

Rename Files

Rename a file

    $filesystem->rename($path, $newPath);

Where:

Variable Type Description
$path string Path to the existing file
$newPath string The new path of the file

Delete Files

Delete a file.

    $filesystem->delete($path);

Where:

Variable Type Description
$path string The target file

Note: The delete() method will throw a `\Bolt\Filesystem\Exception\FileNotFoundException` if you attempt to delete a non-existing file, use exists() to check its existance, or try/catch if preferred.



Edit this page on GitHub
Couldn't find what you were looking for? We are happy to help you in the forum, on Slack or on Github.