本文目录导读:

我来详细介绍PHP项目对接私有存储服务的开发方法,涵盖主流私有存储系统的对接方案。
常见私有存储系统
MinIO - 开源对象存储
// 使用AWS SDK for PHP
composer require aws/aws-sdk-php
// MinIO对接示例
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
class MinIOStorage {
private $client;
private $bucket;
public function __construct() {
$this->client = new S3Client([
'version' => 'latest',
'region' => 'us-east-1',
'endpoint' => 'http://your-minio-server:9000',
'use_path_style_endpoint' => true,
'credentials' => [
'key' => 'your-access-key',
'secret' => 'your-secret-key',
],
]);
$this->bucket = 'your-bucket';
}
// 上传文件
public function uploadFile($localPath, $objectName) {
try {
$result = $this->client->putObject([
'Bucket' => $this->bucket,
'Key' => $objectName,
'SourceFile' => $localPath,
]);
return $result['ObjectURL'];
} catch (AwsException $e) {
throw new \Exception("上传失败: " . $e->getMessage());
}
}
// 生成预签名URL(临时访问)
public function getPresignedUrl($objectName, $expires = 3600) {
$cmd = $this->client->getCommand('GetObject', [
'Bucket' => $this->bucket,
'Key' => $objectName
]);
$request = $this->client->createPresignedRequest($cmd, "+{$expires} seconds");
return (string) $request->getUri();
}
}
FastDFS - 分布式文件系统
// 使用fastdfs客户端扩展
// 安装:pecl install fastdfs
class FastDFSStorage {
private $tracker;
private $storage;
public function __construct() {
// 加载配置文件
$config = [
'tracker_server' => '192.168.1.100:22122',
'connect_timeout' => 5,
'network_timeout' => 30
];
// 连接tracker
$this->tracker = fastdfs_tracker_get_connection();
$this->storage = fastdfs_tracker_query_storage_store();
}
// 上传文件
public function uploadFile($localFile, $fileExt = '') {
$fileInfo = fastdfs_storage_upload_by_filename(
$localFile,
$fileExt,
[],
$this->tracker,
$this->storage
);
if ($fileInfo) {
return [
'group_name' => $fileInfo['group_name'],
'remote_filename' => $fileInfo['filename']
];
}
return false;
}
// 下载文件
public function downloadFile($groupName, $remoteFilename) {
return fastdfs_storage_download_file_to_buff(
$groupName,
$remoteFilename
);
}
}
Ceph - 分布式存储
// 使用Ceph的RADOS网关(S3兼容)
// 同样可以使用AWS SDK for PHP
// Ceph Rados Gateway对接
class CephStorage {
private $s3Client;
public function __construct() {
$this->s3Client = new S3Client([
'version' => 'latest',
'region' => 'default',
'endpoint' => 'http://ceph-rgw:7480',
'use_path_style_endpoint' => true,
'credentials' => [
'key' => 'ceph-access-key',
'secret' => 'ceph-secret-key',
],
]);
}
// 分片上传大文件
public function multipartUpload($localFile, $objectKey) {
$uploader = new MultipartUploader($this->s3Client, $localFile, [
'bucket' => 'your-bucket',
'key' => $objectKey,
'acl' => 'private',
'before_initiate' => function (\Aws\Command $command) {
$command['ContentType'] = 'application/octet-stream';
},
'before_upload' => function (\Aws\Command $command) {
$command['CacheControl'] = 'max-age=3600';
},
]);
try {
$result = $uploader->upload();
return $result['ObjectURL'];
} catch (MultipartUploadException $e) {
$uploader->abort();
throw $e;
}
}
}
通用存储抽象层设计
策略模式实现多存储切换
<?php
// 存储接口
interface StorageInterface {
public function upload($localPath, $remotePath);
public function download($remotePath, $localPath);
public function delete($path);
public function exists($path);
public function getUrl($path);
}
// MinIO实现
class MinIOStorageAdapter implements StorageInterface {
// ... 实现代码
}
// FastDFS实现
class FastDFSStorageAdapter implements StorageInterface {
// ... 实现代码
}
// 存储管理器
class StorageManager {
private $adapter;
public function __construct(StorageInterface $adapter) {
$this->adapter = $adapter;
}
public function uploadFile($localFile, $remoteFile) {
return $this->adapter->upload($localFile, $remoteFile);
}
public function downloadFile($remoteFile, $localFile) {
return $this->adapter->download($remoteFile, $localFile);
}
}
// 使用示例
$config = require 'config/storage.php';
switch ($config['driver']) {
case 'minio':
$adapter = new MinIOStorageAdapter($config['minio']);
break;
case 'fastdfs':
$adapter = new FastDFSStorageAdapter($config['fastdfs']);
break;
default:
throw new \Exception("不支持的存储类型");
}
$storage = new StorageManager($adapter);
$storage->uploadFile('/tmp/test.jpg', 'images/test.jpg');
高级功能实现
断点续传
class ResumeUpload {
public function uploadInChunks($file, $remotePath, $chunkSize = 5 * 1024 * 1024) {
$uploadId = $this->initiateMultipartUpload($remotePath);
$parts = [];
$partNumber = 1;
$handle = fopen($file, 'rb');
while (!feof($handle)) {
$chunk = fread($handle, $chunkSize);
$etag = $this->uploadPart($uploadId, $partNumber, $chunk);
$parts[] = [
'ETag' => $etag,
'PartNumber' => $partNumber
];
$partNumber++;
}
fclose($handle);
return $this->completeMultipartUpload($uploadId, $parts);
}
}
文件处理中间件
class StorageMiddleware {
public function handleFileUpload($request, $next) {
// 文件验证
$file = $request->file('file');
$validator = new FileValidator();
if (!$validator->validate($file)) {
throw new ValidationException("文件验证失败");
}
// 文件处理
$processor = new FileProcessor();
$processed = $processor->compress($file->path());
// 上传到存储
$result = $next($processed);
// 清理临时文件
unlink($processed);
return $result;
}
}
缓存层实现
class CachedStorage {
private $storage;
private $cache;
public function __construct($storage, $cache = null) {
$this->storage = $storage;
$this->cache = $cache ?: new RedisCache();
}
public function getUrl($path) {
$cacheKey = "storage_url_{$path}";
if ($cached = $this->cache->get($cacheKey)) {
return $cached;
}
$url = $this->storage->getUrl($path);
$this->cache->set($cacheKey, $url, 3600); // 缓存1小时
return $url;
}
}
配置文件示例
config/storage.php
<?php
return [
'default' => env('STORAGE_DRIVER', 'minio'),
'drivers' => [
'minio' => [
'endpoint' => env('MINIO_ENDPOINT', 'http://192.168.1.100:9000'),
'access_key' => env('MINIO_ACCESS_KEY'),
'secret_key' => env('MINIO_SECRET_KEY'),
'bucket' => env('MINIO_BUCKET', 'default'),
'region' => env('MINIO_REGION', 'us-east-1'),
'use_ssl' => env('MINIO_USE_SSL', false),
],
'fastdfs' => [
'tracker_server' => env('FASTDFS_TRACKER', '192.168.1.100:22122'),
'group_name' => env('FASTDFS_GROUP', 'group1'),
'connect_timeout' => env('FASTDFS_CONNECT_TIMEOUT', 5),
'network_timeout' => env('FASTDFS_NETWORK_TIMEOUT', 30),
],
'ceph' => [
'endpoint' => env('CEPH_ENDPOINT', 'http://192.168.1.100:7480'),
'access_key' => env('CEPH_ACCESS_KEY'),
'secret_key' => env('CEPH_SECRET_KEY'),
'bucket' => env('CEPH_BUCKET', 'default'),
],
],
'settings' => [
'max_file_size' => env('MAX_FILE_SIZE', 100 * 1024 * 1024), // 100MB
'allowed_extensions' => ['jpg', 'png', 'pdf', 'doc'],
'cache_enabled' => env('STORAGE_CACHE', true),
'cache_ttl' => env('STORAGE_CACHE_TTL', 3600),
]
];
使用示例
// 初始化存储
$storage = new StorageManager(
StorageFactory::create(config('storage.default'))
);
// 上传文件
try {
$result = $storage->uploadFile(
'/tmp/document.pdf',
'documents/2024/01/document.pdf'
);
echo "上传成功: " . $result;
} catch (StorageException $e) {
echo "上传失败: " . $e->getMessage();
}
// 生成临时访问链接
$url = $storage->getTemporaryUrl(
'documents/2024/01/document.pdf',
3600 // 1小时有效
);
这样就可以灵活对接各种私有存储系统,同时保持代码的可维护性和扩展性,选择哪种方案取决于你的具体需求和基础设施条件。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播