Laravel Google Cloud Storage 使用教程
1. 项目的目录结构及介绍
spatie/laravel-google-cloud-storage
├── src
│ ├── GoogleCloudStorageServiceProvider.php
│ ├── GoogleCloudStorageAdapter.php
│ └── ...
├── tests
│ ├── GoogleCloudStorageAdapterTest.php
│ └── ...
├── .editorconfig
├── .gitattributes
├── .gitignore
├── .php_cs.dist
├── CHANGELOG.md
├── LICENSE.md
├── README.md
├── composer.json
├── phpunit.xml.dist
├── psalm.xml.dist
└── testbench.yaml
目录结构说明
src/
: 包含项目的主要源代码文件,如服务提供者(GoogleCloudStorageServiceProvider.php
)和适配器(GoogleCloudStorageAdapter.php
)。tests/
: 包含项目的测试文件,如适配器测试(GoogleCloudStorageAdapterTest.php
)。.editorconfig
,.gitattributes
,.gitignore
: 配置文件,用于代码格式化和版本控制。.php_cs.dist
: PHP CS Fixer 配置文件。CHANGELOG.md
,LICENSE.md
,README.md
: 项目文档,包括变更日志、许可证和使用说明。composer.json
: Composer 依赖管理文件。phpunit.xml.dist
,psalm.xml.dist
: 测试和静态分析配置文件。testbench.yaml
: Laravel 测试工具配置文件。
2. 项目的启动文件介绍
GoogleCloudStorageServiceProvider.php
namespace Spatie\GoogleCloudStorage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use Google\Cloud\Storage\StorageClient;
class GoogleCloudStorageServiceProvider extends ServiceProvider
{
public function boot()
{
// 注册配置文件
$this->publishes([
__DIR__.'/../config/google-cloud-storage.php' => config_path('google-cloud-storage.php'),
]);
// 注册文件系统适配器
$this->app->bind('google-cloud-storage', function ($app) {
$config = config('google-cloud-storage');
$storageClient = new StorageClient([
'projectId' => $config['project_id'],
'keyFilePath' => $config['key_file_path'],
]);
$bucket = $storageClient->bucket($config['bucket']);
return new Filesystem(new GoogleCloudStorageAdapter($bucket));
});
}
public function register()
{
// 合并配置文件
$this->mergeConfigFrom(
__DIR__.'/../config/google-cloud-storage.php', 'google-cloud-storage'
);
}
}
启动文件说明
GoogleCloudStorageServiceProvider.php
: 服务提供者文件,负责注册配置文件和文件系统适配器。boot()
方法: 发布配置文件并绑定文件系统适配器到应用程序。register()
方法: 合并配置文件到应用程序配置中。
3. 项目的配置文件介绍
config/google-cloud-storage.php
return [
'project_id' => env('GOOGLE_CLOUD_PROJECT_ID', 'your-project-id'),
'key_file_path' => env('GOOGLE_CLOUD_KEY_FILE', null),
'bucket' => env('GOOGLE_CLOUD_STORAGE_BUCKET', 'your-bucket-name'),
];
配置文件说明
project_id
: Google Cloud 项目 ID,从环境变量中读取或使用默认值。key_file_path
: 服务账号密钥文件路径,从环境变量中读取或使用默认值。bucket
: 存储桶名称,从环境变量中读取或使用默认值。
以上是 Laravel Google Cloud Storage 项目的目录结构、启动文件和配置文件的详细介绍。通过这些信息,您可以更好地理解和使用该项目。