laravel 9 升级至 flysystem 3 后,`storage::disk('s3')->getdriver()->getadapter()->getclient()` 不再可用;本文详解兼容方案——通过宏(macro)动态扩展 `awss3v3adapter`,快速恢复对底层 `aws\s3\s3client` 的访问能力,并提供完

在 Laravel 9 中,由于 Flysystem 3 的架构调整,原有的适配器链式调用(如 getDriver()->getAdapter()->getClient())已被移除。Storage::disk('s3') 返回的是 Illuminate\Filesystem\FilesystemAdapter 实例,而其底层不再暴露 getAdapter() 方法;更重要的是,Laravel 官方已将 AWS S3 适配器逻辑封装为 Illuminate\Filesystem\AwsS3V3Adapter(注意命名中的 V3),该类直接持有 Aws\S3\S3Client 实例,但默认未提供公开访问方法。
幸运的是,Laravel 的 FilesystemAdapter 及其子类均继承自 Macroable,支持运行时方法注入。因此,最简洁、低侵入的临时解决方案是:为 AwsS3V3Adapter 注册一个 getClient 宏,直接返回其私有属性 $client。
在 app/Providers/AppServiceProvider.php 的 boot() 方法中添加:
use Illuminate\Filesystem\AwsS3V3Adapter;
use Illuminate\Support\Facades\Storage;
public function boot()
{
// 为 AWS S3 V3 适配器注入 getClient 宏
AwsS3V3Adapter::macro('getClient', function () {
return $this->client;
});
}⚠️ 注意:确保此宏注册在 Storage::disk() 被首次调用之前(通常 boot() 方法已满足),且仅需注册一次。
之后,你即可像 Laravel 8 一样直接使用:
use Illuminate\Support\Facades\Storage;
$client = Storage::disk('s3')->getClient(); // ✅ 返回 Aws\S3\S3Client 实例
$bucket = config('filesystems.disks.s3.bucket');
$key = 'uploads/photo.jpg';
$result = $client->createMultipartUpload([
'Bucket' => $bucket,
'Key' => $key,
'ContentType' => 'image/jpeg',
'ContentDisposition' => 'inline',
]);
return response()->json([
'uploadId' => $result['UploadId'],
'key' => $result['Key'],
]);/** @var \Aws\S3\S3Client $client */
$client = Storage::disk('s3')->getClient();Laravel 9 的 Flysystem 3 迁移虽移除了旧有适配器访问路径,但凭借 Laravel 强大的宏机制,我们能以极小代价无缝复用原有 S3 分段上传逻辑。只需一行宏注册 + 一行调用,即可稳定对接 Aws\S3\S3Client —— 这既是向后兼容的务实之选,也体现了 Laravel “约定优于配置”与“可扩展性优先”的设计哲学。