文件上傳類需配置:上傳大小限制、允許類型、命名規範、目錄創建規則等。
ThinkPHP / Laravel 早期風格
$upload = new UploadFile(); // 實例化
$upload->maxSize = 3145728; // 3MB
$upload->allowExts = ['jpg','gif','png','jpeg'];
$upload->savePath = './Uploads/images/';
$upload->saveRule = 'uniqid'; // 命名規則
$upload->upload(); // 執行上傳
現代框架(Symfony, Laravel 服務容器)推薦
class UploadFile {
private $config;
public function __construct(array $config = []) {
$this->config = array_merge([
'maxSize' => 2097152,
'allowExts' => ['jpg','png','gif'],
'savePath' => './uploads/',
'saveRule' => 'md5',
], $config);
}
}
// 使用
$upload = new UploadFile([
'maxSize' => 5242880,
'savePath' => './Uploads/avatar/',
]);
參數極多時的最佳實踐
class UploadConfig {
public int $maxSize = 2097152;
public array $allowExts = ['jpg','png','gif'];
public string $savePath = './uploads/';
public string $saveRule = 'uniqid';
public bool $createSubDir = true;
}
class UploadFile {
private UploadConfig $config;
public function __construct(UploadConfig $config = null) {
$this->config = $config ?? new UploadConfig();
}
}
// 使用
$config = new UploadConfig();
$config->maxSize = 5242880;
$config->savePath = './Uploads/avatar/';
$upload = new UploadFile($config);
class UploadFile {
private $config;
private function __construct() {}
public static function create(): self { return new self(); }
public function maxSize(int $bytes): self { $this->config['maxSize'] = $bytes; return $this; }
public function allowExts(array $exts): self { $this->config['allowExts'] = $exts; return $this; }
public function savePath(string $path): self { $this->config['savePath'] = $path; return $this; }
public function upload(): array { /* ... */ }
}
// 使用
$result = UploadFile::create()
->maxSize(5242880)
->allowExts(['jpg','png'])
->savePath('./Uploads/avatar/')
->upload();
| 框架 | 風格 | 特點 |
|---|---|---|
| ThinkPHP 3/5 | Setter 注入 | 屬性公開,鏈式調用 |
| Laravel | 配置文件 + 服務容器綁定 | config/filesystems.php 集中配置,運行時解析 |
| Symfony | OptionsResolver + 依賴注入 | 嚴格驗證配置選項,編譯時檢查 |
| Yii2 | 屬性配置 + 行為綁定 | ['class' => Upload::class, 'maxSize' => ...] |