Skip to content

About

yii2 components & adapter for league/flysystem:^3.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

60 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

handcode/yii2-flysystem

yii2 components & adapters for league/flysystem:^3.0

Base Concept

The goal of this package is to be able to configure and use league/flysystem adapters in yii2.

Therefor this package provide yii2 components, interfaces and some decorator adapters for the league/flysystem:^3.0

It’s all about adapting (Quote from flysystem architecture docs)

To get an idea of the base concept of this package, see the Architecture & Design of the league/flysystem. In the "Consuming Flysystem" chapter, this package is the Your Code in the composition picture.

If you want to change or extend the basic functionality provided by this package, you can write and add your own custom (decorator) adapters and add them to the base adapter via component config.

See Adapter chapter below

Interfaces

To ensure a unified api for the flysystem adapters inside yii2, the packages provide 2 interfaces which extends the League\Flysystem\FilesystemOperator interface.

interface extends implements description
StorageInterface yii\base\Component \League\Flysystem\FilesystemOperator Extends the FilesystemOperator interface
define some convenience methods for listing items by type
StorageComponentInterface yii\base\Component \handcode\flysystem\interfaces\StorageInterface Extends the StorageInterface interface
define properties (getter/setter) amd methods to be able to configure and use StorageInterface objects as yii2 components

Components

This package provide one Component for single Storage and one for MountManager FilesystemOperator of the league/flysystem

Both components implement the StorageInterface.

  • The Storage component is the one which must be used to define the real flysystem storages in yii and therefor implements the \handcode\flysystem\interfaces\StorageComponentInterface
  • The MountManager component implements the \handcode\flysystem\interfaces\StorageInterface and can be used to work with multiple StorageComponentInterface instances.

Storage

This is the main component to define a flysystem FilesystemAdapter and use it as a yii2 component.

Component Properties

The "behavior" of the storage can be changed and expanded using the component properties:

  • scope "visible" Storage to a subDir of the AdapterRoot
  • make Storage readOnly
  • define how directories are handled (rm -f, mkdir -p)
  • filter lists with callback
  • add/modify extraMetaData with callback
  • populate MimeType in listContent
  • add Custom Decorator Adapters
  • ...

TBD: docs & examples

meanwhile, read the code Luke

property: filterCallback

can be used to define a callable that will be used das filter in listContent

example: define a readonly storage, with a simple filterCallback to ensure only files will be listed and all dirs are "hidden"

        'fileOnlyStorage' => [
            'class' => \handcode\flysystem\components\Storage::class,
            'readOnly' => true,
            'filterCallback' => function ($storageAttributes) {
                return ($storageAttributes->type() === StorageAttributes::TYPE_FILE);
            },
            'adapter' => function() {
                return new LocalFilesystemAdapter(
                    '/app/web/public'
                );
            }
        ],...

Usage examples

# get component instance from yii2 app
$storage = \Yii::$app->get('devStorage');

# get Generator with items in root, as path param is required here, use empty string for root
$storage->listContents('');
# get Generator with all items in the filesystem (recursive list)
$storage->listContents('', true);
# get items in root as array
$storage->listContents('')->toArray();
# use convenience list methods from the Storage component
# list all files and dirs in fs root. slashes are "normalized",
# so path values '/', '' or "no param, which will use the default  '' " are all equal and point to the root of the FS
$storage->list();
# list all files and dirs in FS (recursive list), here we MUST set the first param as empty string to be able to set second param 
$storage->list('', true);
# get items in root sorted by path name as array
$storage->list('')->sortByPath()->toArray()
# list all files and dirs in subdir
# slashes are "normalized", so 'a', '/a', 'a/', '/a/' will all use '<root>/a'
$storage->list('a/');
# list all files in subdir
$storage->files('a');
# get all files in subdir as array
$storage->files('a')->toArray();
# list all directories in the FS (recursive)
$storage->directories('', true);
# ... you get the idea, right?

# read content of a file
$storage->read('test.txt');
# create a file
$storage->write('a/test-write.txt', 'funny test file content....');
# create directory
$storage->createDirectory('a');
# copy a file
$storage->copy('test.txt', 'a/test-copy.txt');
# move/rename a dir
$storage->move('a', 'a2');
# check if given path exists (as file or dir)
$storage->has('test.txt');
# check if path exists as file
$storage->fileExists('a/test.txt');
# check if path exists as dir
$storage->directoryExists('a');
# ....

MountManager

To get an idea of the base concept behind the MountManager, see the league/flysystem MountManager docs

In addition to the both "special treated methods" move and copy mentioned in the flysystem docs, the MountManager component provide a rsync method, which can be used to easily sync parts of, or whole filesystems.

To see how MountManager components can be defined, see config examples below.

MountManager::rsync() usage
/** @var \handcode\flysystem\components\MountManager $manager */
$manager = \Yii::$app->get('fsManager');
$manager->rsync('local://a', 'local2://')

As for unix rsync, trailing slashes in src path are important but have no effect in dst path. Examples:

  • f1://a -> f2:// will sync f1://a -> f2://a
  • f1://a -> f2://b will sync f1://a -> f2://b/a
  • f1://a -> f2://b/ will sync f1://a -> f2://b/a
  • f1://a/ -> f2://b will sync f1://a/* -> f2://b/*
  • f1://a/ -> f2://b/ will sync f1://a/* -> f2://b/*

Adapter

This package provide some Decorator Adapter that can/are wrapped around the FilesystemAdapter of the league/flysystem.

Decorator Adapter

Default Decorator Adapters

Some Default Adapters can be used without "special" Code simply by setting Component properties

property added if value Adapter used Adapter can be overloaded in
scope $string League\Flysystem\PathPrefixing\PathPrefixedAdapter components\Storage::getPathPrefixedAdapter
readOnly true League\Flysystem\ReadOnly\ReadOnlyFilesystemAdapter components\Storage::getReadOnlyAdapter
createDirOnDemand false adapters\ParentMustExistAdapter components\Storage::getParentMustExistAdapter
deleteDirRecursive false adapters\DeleteOnlyEmptyDirAdapter components\Storage::getDeleteOnlyEmptyDirAdapter

Other Adapters

ListCacheAdapter

ListCacheAdapter is a flysystem Adapter which cache results for:

  • listContents
  • fileExists & directoryExists
  • metaData like fileSie, mimeType and lastModified

see: handcode\flysystem\adapters\ListCacheAdapter

Parameters:

name type required default
$adapter FilesystemAdapter yes
$cache string|Cache|callable yes
$cachePrefix null|string|callable yes __CLASS__
$cacheTTL null|int no 60

The Adapter simply use \yii\caching\Cache as caching layer which significantly improves reading speed if e.g. external FS like FTP is used.

It also can be seen as the POC/Reference implementation for other more complex "caching" Adapters. Use case could be: implementation of a fast file-search with ActiceRecord and DB-table as caching layer where the FS-MetaData is cache / stored.

Custom Adapters

More Decorator/Adapters can be set/added by defining them in the yii app config via Component.decoratorAdapter property.

In this way, one can extend/change the behaviour by wrapping methods of the underlying FilesystemAdapter. By extending your adapters from \League\Flysystem\DecoratedAdapter, these can be quite simple, as you must only implement those methods from the FilesystemAdapter interface for which you will change the behaviour.

To get an idea how such an adapter can be implemented, see the implementation of the above-mentioned default Decorator Adapters.

Since the adapters are wrapped around each other, the order in which they are defined is important!

Config

Basic example

Component with LocalFilesystemAdapter for the public folder in the docRoot.

        'publicWebStorage' => [
            'class' => \handcode\flysystem\components\Storage::class,
            'adapter' => function() {
                return new LocalFilesystemAdapter(
                    '/app/web/public'
                );
            }
        ],

Example with decorator adapters

The next yii2 component config use some of the default Adapters by setting component properties (scope, createDirOnDemand,... ) and adds a Caching Adapter, initialized with the Yii::$app->cache component.

The virtual root of the FS component will be /app/web/public/images, which is build from the base path of the LocalFilesystemAdapter + the configured scope for which the League\Flysystem\PathPrefixing\PathPrefixedAdapter is added from the Storage component.

        'imgStorage' => [
            'class' => \handcode\flysystem\components\Storage::class,
            'readOnly' => false,
            'scope' => 'images',
            'createDirOnDemand' => false,
            'deleteDirRecursive' => false,
            'adapter' => function() {
                return new LocalFilesystemAdapter(
                    '/app/web/public'
                );
            },
            'decoratorAdapter' => [
                function ($adapter) {
                    return new \handcode\flysystem\adapters\ListCacheAdapter($adapter, Yii::$app->cache, 'imgStorage', 600);
                }
            ]
        ],

Example with MountManager

Here with define 2 scoped Storage components within the same base path and one MountManager Component to manage operations between the both Storage components.

        'localStorage' => [
            'class' => \handcode\flysystem\components\Storage::class,
            'scope' => 'fs-local',
            'adapter' => function() {
                return new LocalFilesystemAdapter(
                    '/app/web/public'
                );
            }
        ],
        'local2Storage' => [
            'class' => \handcode\flysystem\components\Storage::class,
            'scope' => 'fs-local-2',
            'adapter' => function() {
                return new LocalFilesystemAdapter(
                    '/app/web/public'
                );
            }
        ],
        // manager for both of the storage components
        'fsManager' => [
           'class' => \handcode\flysystem\components\MountManager::class,
           'storageComponents' => [
               'local' => 'localStorage',
               'local2' => 'local2Storage'
           ],
        ],

If you do not need one or all Storage components "outside" of the manager, these can also be defined in the manager config. This config create a manager with both Storage components from the last example with the difference, that the local2Storage Storage can not be used "outside" of the manager.

        'localStorage' => [
            'class' => \handcode\flysystem\components\Storage::class,
            'scope' => 'fs-local',
            'adapter' => function() {
                return new LocalFilesystemAdapter(
                    '/app/web/public'
                );
            }
        ],
        // manager for the defined localStorage storage component and one storage component which is not accessible "outside" the manager
        'fsManager' => [
           'class' => \handcode\flysystem\components\MountManager::class,
           'storageComponents' => [
               'local' => 'localStorage',
               'local2' => [
                   'class' => \handcode\flysystem\components\Storage::class,
                   'scope' => 'fs-local-2',
                   'adapter' => function() {
                       return new LocalFilesystemAdapter(
                           '/app/web/public'
                       );
                   }
               ]
           ],
        ],

helper

The package provide helper class for generic tasks.

\handcode\flysystem\helper\StorageHelper

Currently, to handle StorageAttributes. These are currently still somewhat cumbersome to use in the flysystem package if, for example, you want to add extraMetaData.

It is highly recommended to use the helper methods to have one place if flysystem wil change the StorageAttributes interface some day.

method desc
StorageHelper::storageAttributesMap get an array with StorageAttribute keys and the methods to get their values
StorageHelper::storageAttributesMerge change (merge) StorageAttribute values with/from given array

About

yii2 components & adapter for league/flysystem:^3.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages