现在的文件、图片等上传基本都在使用oss存储。而现在常用的oss存储有阿里云、腾讯云、七牛云、华为云等,但是用的最多的还是前三种。而我主要封装的是本地存储、阿里云存储、腾讯云存储、七牛云存储。废话不多说,直接上传设计图及说明,就一目了然咯。
一、上传父抽象类开发
在根目录下extend文件夹里创建文件夹并命名为Upload,然后创建上传父抽象类文件并命名为UploadHandle。切记,本类里一定要加上abstract关键字,不仅要类加上,方法也要加上。代码如下:
<?php
/**
* 上传父抽象类
* User: 龙哥 三年风水
* Date: 2024/11/2/0002
* Time: 17:47
*/
namespace Upload;
abstract class UploadHandle
{
/**
* 上传操作
* @ param $object 加密后的文件
* @ param $filePath 临时存放的文件路径
* @ return mixed
*/
abstract function uploadFile($object, $filePath);
/**
* 删除操作
* @ param $object 具体的文件地址
* @ return mixed
*/
abstract function deleteFile($object);
}
二、上传文件工厂控制类
在根目录下extend文件夹里创建文件夹并命名为Upload,然后创建上传文件工厂控制类并命名为UploadFactory。代码如下:
<?php
/**
* 上传文件工厂控制类
* User: 龙哥 三年风水
* Date: 2024/11/2/0002
* Time: 18:06
*/
namespace Upload;
use Error\BaseError;
use app\model\param\Upload as UploadModel;
use Upload\channel\LocalUpload;
use Upload\channel\AliyunUpload;
use Upload\channel\TencentUpload;
use Upload\channel\QiniuyunUpload;
class UploadFactory
{
public static $instance=null;//缓存实例
protected $uploadType = 0;通道类型
protected $channel = [];//通道参数
/**
* 初始化
* User: 龙哥·三年风水
* Date: 2024/4/8
* Time: 15:26
* UploadFactory constructor.
*/
public function __construct($channel){
$res = UploadModel::dataFind(['id' => 1],'upload_type,example_name,access_key,secret_key,bucket_name,domain_name');
if(empty($res))throw new BaseError("上传通道参数未配置",50000,200);
$this->uploadType = $res['upload_type'];
if($this->uploadType != 1){
$this->channel = [
"name" => $res['name'],
"access_key" => $res['access_key'],
"secret_key" => $res['secret_key'],
"bucket" => $res['bucket'],
"domain_name" => $res['domain_name']
];
}
return $this->getUploadHandle();
}
/**
* 调用上传通道
* @ return null|AliyunUpload|LocalUpload|QiniuyunUpload|TencentUpload
*/
private function getUploadHandle(){
switch ((int)$this->uploadType){
case 1:
self::$instance = new LocalUpload();
break;
case 2:
self::$instance = new AliyunUpload($this->channel);
break;
case 3:
self::$instance = new TencentUpload($this->channel);
break;
case 4:
self::$instance = new QiniuyunUpload($this->channel);
break;
default:
self::$instance = null;
throw new BaseError("未设置任何文件上传通道",50000,200);
break;
}
return self::$instance;
}
}
三、提前说明
其实这个上传文件工厂控制类还是可以优化的,可以改成自动识别上传工厂类,不需要使用switch方法。明天将实现四个上传工厂类。