如何使用依赖注入来包装 League Flysystem

How To Wrap League Flysystem with Dependency Injection

目标是创建一个 Reader class,它是 League Flysystem 之上的包装器documentation

Reader 应该提供方便的方式来读取目录中的所有文件,无论文件物理形式如何(本地文件或存档中的文件)

由于 DI 方法,包装器不应在其内部创建依赖项实例,而是将这些依赖项作为参数传入构造函数或其他 setter 方法。

这是一个示例如何单独使用 League Flysystem(没有提到的包装器) 从磁盘读取常规文件:

<?php
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local;

$adapter = new Local(__DIR__.'/path/to/root');
$filesystem = new Filesystem($adapter);
$content = $filesystem->read('path-to-file.txt');

正如您首先看到的,您创建了一个 适配器 Local ,它在其构造函数中需要路径 然后你创建文件系统,它需要在其构造函数中使用适配器实例。

两者的参数:FilesystemLocal 不是可选的。从这些 classes 创建对象时必须传递它们。 两个 classes 也没有任何 public setters 用于这些参数。

我的问题是如何使用依赖注入来编写Reader class来包装Filesytem和Local?

我通常会做类似的事情:

<?php

use League\Flysystem\FilesystemInterface;
use League\Flysystem\AdapterInterface;

class Reader
{
    private $filesystem;
    private $adapter

    public function __construct(FilesystemInterface $filesystem, 
                                AdapterInterface $adapter)
    {
        $this->filesystem = $filesystem;
        $this->adapter = $adapter;
    }    

    public function readContents(string $pathToDirWithFiles)
    {
        /**
         * uses $this->filesystem and $this->adapter
         * 
         * finds all files in the dir tree
         * reads all files
         * and returns their content combined
         */
    }
}

// and class Reader usage
$reader = new Reader(new Filesytem, new Local);
$pathToDir = 'someDir/';
$contentsOfAllFiles = $reader->readContents($pathToDir);

//somwhere later in the code using the same reader object
$contentsOfAllFiles = $reader->readContents($differentPathToDir);

但这行不通,因为我需要将本地适配器传递给 文件系统构造函数,为了做到这一点,我需要传递给 本地适配器路径优先,完全违背整点 Reader 的使用方便性只是将路径传递给目录 所有文件都在哪里,Reader 完成所有需要完成的工作 只用一种方法 readContents() 来提供这些文件的内容。

所以我卡住了。 是否有可能实现 Reader 作为 Filestem 及其本地适配器的包装器?

我想在使用关键字 new 的地方避免紧耦合并以这种方式获取依赖项的对象:

<?php
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local;

class Reader
{
    public function __construct()
    {
    }    

    public function readContents(string $pathToDirWithFiles)
    {

        $adapter = new Local($pathToDirWithFiles);
        $filesystem = new Filesystem($adapter);

        /**
         * do all dir listing..., content reading
         * and returning results.
         */
    }
}

问题:

  1. 有没有办法编写一个包装器,以依赖注入方式使用文件系统和本地作为依赖项?

  2. 是否有除包装器(适配器)之外的任何其他模式可以帮助构建 Reader class 而无需与文件系统和本地紧密耦合?

  3. 暂时完全忘记了 Reader class:如果 Filesystem 在其构造函数中需要 Local 实例并且 Local 在其构造函数中需要字符串(目录路径),那么是否可以以合理的方式在依赖注入容器(Symfony 或 Pimple)中使用这些 classes? DIC 不知道将什么路径 arg 传递给本地适配器,因为稍后将在代码中的某处评估该路径。

1.You 可以使用 FilesystemLocal 作为依赖注入方式的依赖。您可以使用默认路径创建 Adapter 对象和 Filesystem 对象,并将它们传递给 Reader。在 readContents 方法中,您可以使用 help setPathPrefix() 方法修改路径。例如:

class Reader
{
    private $filesystem;
    private $adapter;

    public function __construct(FilesystemInterface $filesystem, 
                                AdapterInterface $adapter)
    {
        $this->filesystem = $filesystem;
        $this->adapter = $adapter;
    }    

    public function readContents(string $pathToDirWithFiles)
    {
        $this->adapter->setPathPrefix($pathToDirWithFiles);
        // some code
    }
}

// usage
$adapter = new Local(__DIR__.'/path/to/root');
$filesystem = new Filesystem($adapter);
$reader = new Reader($filesystem, $adapter);

2.Reader 不是适配器模式,因为它没有实现 League Flysystem 的任何接口。它是 class 用于封装一些与文件系统一起工作的逻辑。您可以阅读有关适配器模式的更多信息 here。您应该使用接口并避免在 class 中直接创建对象以减少 Reader 和文件系统之间的耦合。

3.Yes,您可以在 DIC 中设置适配器的默认路径...

希望我能正确理解你的问题。事实上,我几周前才经历过这个。对我来说这是一些有趣的东西。

Reading through this laravel snippet 帮助我理解了接口和依赖注入的工作原理。这篇文章讨论了契约与外观以及为什么你可能想要使用其中之一。

听起来您希望能够使用一个 Filesystem 实例来读取远程文件(S3 等)或本地文件。由于文件系统只能是远程的或本地的(不是组合),我认为正确的做法是使用一个接口以相同的方式与两者交互,然后允许用户/开发人员选择(通过依赖注入首选项)哪个文件声明 Filesystem.

实例时应使用系统(本地或远程)
// Classes used
use League\Container\Container;
use League\Container\ReflectionContainer;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemInterface;
use League\Flysystem\AwsS3v3\AwsS3Adapter;

// Create your container
$container = new Container;

/**
 * Use a reflection container so devs don't have to add in every 
 * dependency and can autoload them. (Kinda out of scope of the question,
 * but still helpful IMO)
 */
$container->delegate((new ReflectionContainer)->cacheResolutions());

/**
 * Create available filesystems and adapters
 */ 
// Local
$localAdapter = new Local($cacheDir);
$localFilesystem = new Filesystem($localAdapter);
// Remote
$client = new S3Client($args); 
$s3Adapter = new AwsS3Adapter($client, 'bucket-name');
$remoteFilesystem = new Filesystem($s3Adapter);

/**
 * This next part is up to you, and many frameworks do this
 * in many different ways, but it almost always comes down 
 * to declaring a preference for a certain class, or better
 * yet, an interface. This example is overly simple.
 * 
 * Set the class in the container to have an instance of either
 * the remote or local filesystem.
*/
$container->add(
    FileSystemInterface::class,
    $userWantsRemoteFilesystem ? $remoteFilesystem : $localFilesystem
);

Magento 2 does this 通过编译 di.xml 文件并读取您想要替换的 classes,方法是声明对另一个的偏好。

Symfony does this 有点 类似的方式。他们的文档对我来说有点难以理解,但经过几天(连同联赛)的仔细研究后,我终于从另一边走了出来,对正在发生的事情有了很好的了解。

使用您的服务:

假设您的应用程序中有依赖注入,并且您想将 Filesystem 与 reader class 连接起来,您可以将 FilesystemInterface 作为构造函数依赖项,当它被注入时,它将使用你通过 $container->add($class, $service)

传递给容器的任何内容
use League\Flysystem\FilesystemInterface;

class Reader 
{
    protected $filesystem;

    public function __construct(FilesystemInterface $filesystem)
    {
        $this->filesystem = $filesystem;    
    }

    public function getFromLocation($location)
    {
        /**
         * We know this will work, because any instance that implements the
         * FilesystemInterface will have this read method.
         * @see https://github.com/thephpleague/flysystem/blob/dab4e7624efa543a943be978008f439c333f2249/src/FilesystemInterface.php#L27
         * 
         * So it doesn't matter if it is \League\Flysystem\Filesystem or 
         * a custom one someone else made, this will always work and 
         * will be served from whatever was declared in your container.
         */
        return $this->filesystem->read($location);
    }
}

无论何时调用 readContents 方法,您都可以使用工厂模式即时生成 Filesystem

<?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
         */
    }
}

然后您的工厂负责创建正确配置的文件系统对象:

<?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));
    }
}

最后,当您构建 Reader 时,它看起来像这样:

<?php

$reader = new Reader(new LocalFilesystemFactory);
$fooContents = $reader->readContents('/foo');
$barContents = $reader->readContents('/bar');

您将创建文件系统的工作委托给工厂,同时仍然通过依赖注入保持组合的目标。