Laravel 13 配置管理详解
配置管理是 Laravel 应用的核心组成部分,合理的配置管理可以让应用程序更加灵活、可维护。本文将深入探讨 Laravel 13 的配置管理系统。
配置文件结构
标准配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| config/ ├── app.php # 应用配置 ├── auth.php # 认证配置 ├── broadcasting.php # 广播配置 ├── cache.php # 缓存配置 ├── cors.php # CORS 配置 ├── database.php # 数据库配置 ├── filesystems.php # 文件系统配置 ├── hashing.php # 哈希配置 ├── logging.php # 日志配置 ├── mail.php # 邮件配置 ├── queue.php # 队列配置 ├── sanctum.php # Sanctum 配置 ├── services.php # 第三方服务配置 ├── session.php # 会话配置 └── view.php # 视图配置
|
访问配置值
使用 config 辅助函数
1 2 3 4 5
| $value = config('app.name'); $value = config('app.timezone', 'UTC'); $value = config('database.connections.mysql.host');
config(['app.locale' => 'zh']);
|
使用 Config 门面
1 2 3 4 5 6 7 8 9
| use Illuminate\Support\Facades\Config;
$value = Config::get('app.name'); $value = Config::get('app.timezone', 'UTC'); Config::set('app.locale', 'zh');
if (Config::has('app.name')) { }
|
环境配置
.env 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| APP_NAME=Laravel APP_ENV=local APP_KEY=base64:... APP_DEBUG=true APP_URL=http://localhost
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD=
CACHE_DRIVER=redis QUEUE_CONNECTION=redis SESSION_DRIVER=redis
|
env 辅助函数
1 2 3
| $debug = env('APP_DEBUG', false); $name = env('APP_NAME', 'Laravel'); $port = env('DB_PORT', 3306);
|
环境变量类型转换
1 2 3 4 5 6 7 8 9
| APP_DEBUG=true APP_PORT=3306 APP_TAGS=php,laravel,mysql
'debug' => env('APP_DEBUG'), 'port' => env('APP_PORT'), 'tags' => env('APP_TAGS'),
|
配置缓存
缓存配置
1
| php artisan config:cache
|
清除缓存
1
| php artisan config:clear
|
检查缓存状态
1 2 3
| if (app()->configurationIsCached()) { }
|
缓存注意事项
1 2 3 4 5 6 7 8 9 10 11 12
|
'name' => env('APP_NAME', 'Laravel'),
$name = config('app.name');
$name = env('APP_NAME');
|
创建自定义配置
创建配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?php
return [ 'title' => env('BLOG_TITLE', 'My Blog'), 'posts_per_page' => env('BLOG_POSTS_PER_PAGE', 10), 'features' => [ 'comments' => env('BLOG_COMMENTS_ENABLED', true), 'likes' => env('BLOG_LIKES_ENABLED', true), ], 'seo' => [ 'meta_description' => env('BLOG_META_DESCRIPTION'), 'meta_keywords' => env('BLOG_META_KEYWORDS'), ], ];
|
访问自定义配置
1 2 3
| $title = config('blog.title'); $perPage = config('blog.posts_per_page', 10); $commentsEnabled = config('blog.features.comments', true);
|
运行时配置
设置配置值
1 2 3 4
| config(['app.locale' => 'zh']); config(['app.timezone' => 'Asia/Shanghai']);
Config::set('app.locale', 'zh');
|
配置组操作
1 2 3 4 5
| $databaseConfig = Config::get('database'); Config::set('database.connections.sqlite', [ 'driver' => 'sqlite', 'database' => database_path('database.sqlite'), ]);
|
配置验证
验证配置值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Validator;
class AppServiceProvider extends ServiceProvider { public function boot(): void { $this->validateConfig(); }
protected function validateConfig(): void { $required = [ 'app.name', 'app.url', 'database.default', ];
foreach ($required as $key) { if (empty(config($key))) { throw new \RuntimeException("Configuration key '{$key}' is required"); } } } }
|
使用配置验证规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| return [ 'gateway' => env('PAYMENT_GATEWAY'), 'api_key' => env('PAYMENT_API_KEY'), 'secret' => env('PAYMENT_SECRET'), ];
public function boot(): void { if (config('payment.gateway') && !config('payment.api_key')) { throw new \InvalidArgumentException('Payment API key is required'); } }
|
多环境配置
环境特定配置
1 2 3 4 5 6 7 8 9 10 11 12
| return [ 'debug' => env('APP_DEBUG', false), 'providers' => [ ], 'aliases' => [ ], ];
|
环境检测
1 2 3 4 5 6 7 8 9 10 11 12 13
| if (app()->environment('local')) { }
if (app()->environment(['local', 'testing'])) { }
if (app()->environment('production')) { }
$environment = app()->environment();
|
环境特定配置文件
1 2 3 4 5 6 7
| return [ 'stripe' => [ 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), ], ];
|
配置加密
加密配置值
1 2
| php artisan env:encrypt php artisan env:encrypt --key=your-encryption-key
|
解密配置值
1 2
| php artisan env:decrypt php artisan env:decrypt --key=your-encryption-key
|
加密环境变量
1 2 3 4 5 6 7
| APP_KEY=base64:... ENCRYPTION_KEY=base64:...
$encrypted = encrypt('sensitive-data'); $decrypted = decrypt($encrypted);
|
配置与依赖注入
配置注入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <?php
namespace App\Services;
class PaymentService { public function __construct( protected string $gateway, protected string $apiKey, protected string $secret, ) {}
public static function fromConfig(): self { return new self( config('payment.gateway'), config('payment.api_key'), config('payment.secret'), ); } }
|
服务提供者绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?php
namespace App\Providers;
use App\Services\PaymentService; use Illuminate\Support\ServiceProvider;
class PaymentServiceProvider extends ServiceProvider { public function register(): void { $this->app->singleton(PaymentService::class, function ($app) { return new PaymentService( config('payment.gateway'), config('payment.api_key'), config('payment.secret'), ); }); } }
|
配置最佳实践
1. 使用合理的默认值
1 2 3 4 5 6 7 8
| 'per_page' => env('ITEMS_PER_PAGE', 15), 'timezone' => env('APP_TIMEZONE', 'UTC'), 'locale' => env('APP_LOCALE', 'en'),
'per_page' => env('ITEMS_PER_PAGE'), 'timezone' => env('APP_TIMEZONE'),
|
2. 分组相关配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| return [ 'general' => [ 'title' => env('BLOG_TITLE'), 'description' => env('BLOG_DESCRIPTION'), ], 'pagination' => [ 'per_page' => env('BLOG_PER_PAGE', 10), ], 'features' => [ 'comments' => env('BLOG_COMMENTS', true), 'likes' => env('BLOG_LIKES', true), ], ];
|
3. 敏感配置保护
1 2 3 4 5 6 7 8 9 10
| DB_PASSWORD=secret STRIPE_SECRET=sk_live_xxx
'password' => env('DB_PASSWORD'), 'secret' => env('STRIPE_SECRET'),
|
4. 类型安全的配置访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <?php
namespace App\Support;
class ConfigHelper { public static function getInt(string $key, int $default = 0): int { return (int) config($key, $default); }
public static function getBool(string $key, bool $default = false): bool { return (bool) config($key, $default); }
public static function getArray(string $key, array $default = []): array { $value = config($key, $default); return is_array($value) ? $value : $default; }
public static function getString(string $key, string $default = ''): string { return (string) config($key, $default); } }
$perPage = ConfigHelper::getInt('blog.per_page', 10); $enabled = ConfigHelper::getBool('blog.features.comments', true);
|
配置调试
列出所有配置
1 2 3 4
| php artisan tinker >>> config()->all() >>> config('app') >>> config('database.connections')
|
自定义配置命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ConfigShow extends Command { protected $signature = 'config:show {key?}'; protected $description = 'Display configuration values';
public function handle(): int { $key = $this->argument('key');
if ($key) { $this->line(json_encode(config($key), JSON_PRETTY_PRINT)); } else { $this->line(json_encode(config()->all(), JSON_PRETTY_PRINT)); }
return 0; } }
|
总结
Laravel 13 的配置管理系统提供了灵活、强大的配置能力。通过合理使用环境变量、配置缓存和自定义配置文件,可以构建出可维护、可扩展的应用程序。记住在配置文件中使用 env() 函数,在代码中使用 config() 函数,并为配置值设置合理的默认值。敏感信息应该存储在 .env 文件中,并确保该文件不被版本控制追踪。