我需要保存用户上传的文件,目前我只是在本地保存它们,但在某些时候它可能会被更改为存储在云中,例如使用AWS。
我正在寻找一种可以帮助我编写可扩展内容的设计模式。
我看到的问题是每种上传方法都需要不同的参数设置,我还需要一种方法来获取文件上传到的URL,而且我也不想完全将本地文件换成云端需要有一种方法可以让任何方法知道它应该使用哪个上传对象。
我正在使用Laravel 4,所以如果有任何特定的帮助,那将是有用的。
编辑..
从目前为止的答案中,我认为我可以使用Gaufrette一个额外的图层。我可以有一个FileUploadManager类来处理应用程序中的所有文件上传,所以一切都在一个地方。
该类中的每个方法都通过调用工厂来使用所需的Gaufrette实例,该工厂使用必要的选项设置适配器:
class FileUploadManager {
protected $fileSystemFactory;
public __construct(FileSystemFactoryInterface $fileSystemFactory)
{
$this->fileSystemFactory = $fileSystemFactory;
}
public function uploadUserLogo($filename, $content)
{
$filesystem = $this->fileSystemFactory->make('local',array('localdirectory' => 'var/www/public/logos');
$filesystem->write($filename, $content);
}
public function uploadUserCV($filename, $content)
{
$filesystem = $this->fileSystemFactory->make('aws',array('aws_bucket' => 'cvs'));
$filesystem->write($filename, $content);
}
}
class GaufretteFileSystemFactory implements FileSystemFactoryInterface {
use Gaufrette\Filesystem;
public function make($type,$options)
{
switch ($type) {
case 'local':
$adapter = new LocalAdapter($options['localdirectory'], true);
return new Filesystem($adapter);
break;
case 'aws':
$adapter = new AmazonS3Adapter($options['aws_bucket']);
return new Filesystem($adapter);
break;
}
}
}
不确定这是否是一种好方法,我不知道如何处理上传资源的位置,FileUploadManager是否关心如何从外部访问文件?
答案 0 :(得分:1)
您需要一个像Gaufrette这样的抽象层,它支持所有类型的存储层[本地文件系统,AWS ...)。
答案 1 :(得分:0)
为什么不使用策略模式? 这是一个让你入门的模板;
<?php
abstract class FileUploader{
public function uploadFile(){
//insert the code to acquire the current temporary file path here
return $this->moveFile($temporaryFilePath);
}
abstract function moveFile($tempFile);
}
class LocalFileUploader extends FileUploader{
function moveFile($tempFile){
//put the rest of the code you have to move the file to the local directory
return $success ? $success : $error; //return the value you are currently returning from here
}
}
class RemoteFileUploader extends FileUploader{
function moveFile($tempFile){
//put the code here that you will use to upload the file to the remote server
return $success ? $success : $error; //return a success or error from here
}
}
?>
你怎么看?这个和命令模式链是我在共同功能专业化时使用最多的那些