Storage

We need to use storage to save data like cache, images, or CSV files. We can have different storage types. All storage classes use the same interface: quillstack/storage-interface, to make it easier.

Storage interface

Storage interface has been created to keep all storage classes consistent. It requires implementing of five simple methods:

  1. get() - Retrieves the contents of a file.
  2. exists() - Checks if the file exists on the storage.
  3. missing() - Checks if the file is missing from the storage.
  4. save() - Saves the contents to the file.
  5. delete() - Deletes one or more files.

Local storage

Local storage uses native PHP functions like file_get_contents and file_put_contents to read and save files. It also uses is_file and unlink function to check if a file exists on the disk and to delete it.

It's a simple wrapper, but it organises the way how your application works with the local files. It also introduces easy to manage exceptions:

  1. LocalStorageException - General exception, not thrown by this library, but every exception extends it.
  2. LocalFileNotDeletedException - Problem with deleting a file.
  3. LocalFileNotExistsException - Thrown only during an attempt of reading a file that doesn't exist.
  4. LocalFileNotSavedException - Problem with storage a file on disk.

Installation

To install the local storage package, run the standard command using Composer:

  • composer require quillstack/local-storage

The package will be ready to use after that.

Usage

Create a class or inject it as a dependency:

  • use Quillstack\LocalStorage\LocalStorage;
  • $storage = new LocalStorage();
  • $storage->save('var/cache/token.txt', 'muHaloosPps23sKkdsaaBBcei');

If you want to use it as a dependency:

  • use Quillstack\LocalStorage\LocalStorage;
  • public function __construct(private LocalStorage $storage)
  • {
  •     //
  • }
  • public function getTokenFromCache()
  • {
  •     $this->storage->get('var/cache/token.txt');
  • }