用于不同上传文件方式的PHP设计模式


PHP Design Pattern for Varying ways of Uploading Files

我需要保存用户上传的文件,目前我只是在本地保存它们,但在某个时候,它可能会被更改为存储在云中,例如使用AWS。

我正在寻找一种设计模式,可以帮助我编写一些可扩展的东西。

我看到的问题是,每种上传方法都需要不同的参数设置,我还需要一种方法来获取文件上传到的URL,而且我不想完全将本地文件交换到云,所以任何方法都需要一种方式来知道它应该使用哪个上传对象。

我正在使用Laravel 4,所以如果有任何特定的帮助,它将是有用的。

编辑。。

从目前的答案来看,我想我可以用高弗雷特加一层。我可以有一个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应该关心如何从外部访问文件吗?

您需要像Gaufrette这样的抽象层,它支持所有类型的存储层[本地文件系统,AWS…]。

为什么不使用策略模式?这里有一个模板,让你开始;

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

你觉得怎么样?当涉及到公共函数

的专业化时,这个和命令链模式是我使用最多的模式