
在 symfony 应用中,当使用 flysystem 组件管理文件存储时,我们通常会配置多个存储适配器(例如,first.storage 和 second.storage)。标准做法是通过依赖注入将特定的 filesystemoperator 实例注入到服务或控制器的构造函数中。然而,在某些场景下,我们需要根据运行时参数动态选择并获取不同的存储实例,例如在一个文件处理工厂中根据类型参数返回对应的存储服务。直接的构造函数注入无法满足这种动态需求。
Flysystem Bundle 默认将其配置的存储服务注册为私有服务。这意味着你不能直接通过 ContainerInterface 使用其原始服务 ID(如 first.storage)来获取它们,因为私有服务无法从容器外部直接访问。虽然可以通过在服务定义中将 Flysystem 服务设置为 public: true 来解决,但这通常不是推荐的做法,因为它会使应用程序的依赖关系变得不那么明确。
为了在保持 Flysystem 服务默认私有性的同时实现动态获取,我们需要一种更优雅的解决方案。
解决此问题的核心思路是:为每个需要动态访问的 Flysystem 存储服务创建一个公共的别名。然后,通过注入 ContainerInterface 到一个工厂类中,利用这些公共别名来动态检索所需的 FilesystemOperator 实例。
首先,在 config/services.yaml 文件中,为你的 Flysystem 存储服务创建公共别名。这样做的好处是,你无需修改 Flysystem Bundle 注册的原始服务的可见性,而只是提供了一个公共的入口点。
假设你的 Flysystem 配置如下:
# config/packages/flysystem.yaml
flysystem:
storages:
first.storage:
adapter: 'local'
options:
directory: '%kernel.project_dir%/var/storage/first'
second.storage:
adapter: 'local'
options:
directory: '%kernel.project_dir%/var/storage/second'现在,在 config/services.yaml 中为它们创建公共别名:
# config/services.yaml
services:
# ... 其他服务配置
# 为 Flysystem 的 'first.storage' 创建公共别名
# 建议使用清晰的命名约定,例如 'app.storage.<名称>_alias'
app.storage.first_alias:
alias: 'first.storage'
public: true # 必须设置为 true,以便从容器外部访问
# 为 Flysystem 的 'second.storage' 创建公共别名
app.storage.second_alias:
alias: 'second.storage'
public: true # 必须设置为 true通过这种方式,app.storage.first_alias 和 app.storage.second_alias 现在是可从服务容器中直接获取的公共服务,它们指向了对应的 Flysystem 存储实例。
接下来,创建一个工厂类(例如 FileSystemFactory),并在其构造函数中注入 ContainerInterface。这个工厂类将负责根据传入的参数,使用公共别名从容器中获取对应的 FilesystemOperator 实例。
<?php
namespace App\Service; // 假设你的服务在 App\Service 命名空间下
use League\Flysystem\FilesystemOperator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Container\ContainerExceptionInterface;
/**
* FileSystemFactory 负责根据名称动态获取 Flysystem 文件存储实例。
*/
class FileSystemFactory
{
private ContainerInterface $container;
/**
* 构造函数,注入 Symfony 的服务容器。
*
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* 根据存储名称动态获取 Flysystem 文件系统操作器实例。
*
* @param string $storageName 存储的名称(例如 'first' 或 'second'),将用于构建服务别名。
* @return FilesystemOperator 对应的 Flysystem 文件系统操作器实例。
* @throws NotFoundExceptionInterface 如果找不到对应的服务别名。
* @throws ContainerExceptionInterface 如果获取服务时发生其他容器相关的错误。
* @throws \RuntimeException 如果获取到的服务不是 FilesystemOperator 实例。
*/
public function getStorage(string $storageName): FilesystemOperator
{
// 根据传入的存储名称构建完整的服务别名 ID
// 例如,如果 $storageName 是 'first',则服务 ID 为 'app.storage.first_alias'
$serviceId = sprintf('app.storage.%s_alias', $storageName);
// 检查服务是否存在且可访问
if (!$this->container->has($serviceId)) {
throw new NotFoundExceptionInterface(
sprintf('Flysystem storage service "%s" (alias for "%s.storage") not found or not public. ' .
'Please ensure it is defined as a public alias in your services.yaml.',
$serviceId, $storageName
)
);
}
// 从容器中获取服务实例
$storageInstance = $this->container->get($serviceId);
// 验证获取到的实例类型是否正确
if (!$storageInstance instanceof FilesystemOperator) {
throw new \RuntimeException(
sprintf('Service "%s" is not a valid FlysystemOperator instance. ' .
'Expected type %s, got %s.',
$serviceId, FilesystemOperator::class, get_debug_type($storageInstance)
)
);
}
return $storageInstance;
}
}现在,你可以在其他服务或控制器中注入 FileSystemFactory,并利用它来动态获取 Flysystem 存储实例:
<?php
namespace App\Controller; // 或其他服务命名空间
use App\Service\FileSystemFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Container\ContainerExceptionInterface;
class FileController extends AbstractController
{
private FileSystemFactory $fileSystemFactory;
public function __construct(FileSystemFactory $fileSystemFactory)
{
$this->fileSystemFactory = $fileSystemFactory;
}
/**
* @Route("/process-file/{storageType}/{fileName}", name="process_file")
*/
public function processFile(string $storageType, string $fileName): Response
{
try {
// 根据 URL 参数动态获取存储实例
$storage = $this->fileSystemFactory->getStorage($storageType);
// 示例:读取文件内容
if ($storage->fileExists($fileName)) {
$content = $storage->read($fileName);
$this->addFlash('success', sprintf('File "%s" from storage "%s" content: %s', $fileName, $storageType, $content));
} else {
$this->addFlash('warning', sprintf('File "%s" not found in storage "%s".', $fileName, $storageType));
}
} catch (NotFoundExceptionInterface $e) {
$this->addFlash('error', 'Storage type not found: ' . $e->getMessage());
} catch (ContainerExceptionInterface $e) {
$this->addFlash('error', 'Container error: ' . $e->getMessage());
} catch (\RuntimeException $e) {
$this->addFlash('error', 'Runtime error: ' . $e->getMessage());
}
return $this->render('file/index.html.twig'); // 假设你有一个视图来显示消息
}
}// public function __construct(FilesystemOperator $firstStorage, FilesystemOperator $secondStorage) { ... }
// public function getStorage(string $storageName) {
// return match ($storageName) {
// 'first' => $this->firstStorage,
// 'second' => $this->secondStorage,
// default => throw new \InvalidArgumentException('Unknown storage type'),
// };
// }这种方法避免了 ContainerInterface 的直接使用,使得依赖更明确。但当存储数量增多时,构造函数会变得臃肿。对于需要高度动态化或存储数量不确定的场景,本文介绍的公共别名结合 ContainerInterface 的方案更为灵活。
通过为 Flysystem 存储服务创建公共服务别名,并结合 ContainerInterface 在工厂类中进行动态检索,我们成功解决了 Symfony 中动态获取特定 Flysystem 文件存储实例的问题。这种方法既保留了 Flysystem 服务默认的私有性,又提供了灵活、可扩展的动态选择机制,是管理多个文件存储并根据运行时需求切换的有效策略。
以上就是Symfony 中动态获取 Flysystem 特定文件存储实例的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号