How To Wrap League Flysystem with Dependency Injection
You can use the Factory Pattern to generate a Filesystem
on the fly, whenever your readContents
method is called:
<?php
use League\Flysystem\FilesystemInterface;
use League\Flysystem\AdapterInterface;
class Reader
{
private $factory;
public function __construct(LocalFilesystemFactory $factory)
{
$this->filesystem = $factory;
}
public function readContents(string $pathToDirWithFiles)
{
$filesystem = $this->factory->createWithPath($pathToDirWithFiles);
/**
* uses local $filesystem
*
* finds all files in the dir tree
* reads all files
* and returns their content combined
*/
}
}
Your factory is then responsible for creating the properly configured filesystem object:
<?php
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local as LocalAdapter;
class LocalFilesystemFactory {
public function createWithPath(string $path) : Filesystem
{
return new Filesystem(new LocalAdapter($path));
}
}
Finally, when you construct your Reader
, it would look like this:
<?php
$reader = new Reader(new LocalFilesystemFactory);
$fooContents = $reader->readContents('/foo');
$barContents = $reader->readContents('/bar');
You delegate the work of creating the Filesystem to the factory, while still maintaining the goal of composition through dependency injection.