本文目录导读:

在 Laravel 中检测和获取应用环境信息,主要有以下几种常用方法:
获取当前环境
app()->environment() 方法
// 获取当前环境
$environment = app()->environment();
// 或
$environment = \App::environment();
// 检查是否在特定环境
if (app()->environment('local')) {
// 本地环境
}
// 检查多个环境
if (app()->environment(['local', 'staging'])) {
// 本地或预发布
}
// 辅助函数
$env = env('APP_ENV'); // .env 文件中的值
环境检测辅助函数
// 使用辅助函数
if (app()->isLocal()) {
// 本地环境
}
if (app()->isProduction()) {
// 生产环境
}
创建自定义环境检测类
创建一个专用的检测服务类:
<?php
namespace App\Services;
use Illuminate\Contracts\Foundation\Application;
class EnvironmentService
{
protected $app;
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* 获取当前环境
*/
public function current(): string
{
return $this->app->environment();
}
/**
* 是否为本地环境
*/
public function isLocal(): bool
{
return $this->app->environment('local');
}
/**
* 是否为生产环境
*/
public function isProduction(): bool
{
return $this->app->environment('production');
}
/**
* 是否为测试环境
*/
public function isTesting(): bool
{
return $this->app->environment('testing');
}
/**
* 是否为预发布环境
*/
public function isStaging(): bool
{
return $this->app->environment('staging');
}
/**
* 获取环境配置
*/
public function getConfig(): array
{
return [
'environment' => $this->current(),
'debug' => config('app.debug'),
'cache' => config('cache.default'),
'database' => config('database.default'),
'mail' => config('mail.default'),
'queue' => config('queue.default'),
];
}
/**
* 检查当前环境是否为指定的环境
*/
public function isInEnvironments(array $environments): bool
{
return $this->app->environment($environments);
}
}
在控制器中使用
<?php
namespace App\Http\Controllers;
use App\Services\EnvironmentService;
use Illuminate\Http\Request;
class HomeController extends Controller
{
protected $environmentService;
public function __construct(EnvironmentService $environmentService)
{
$this->environmentService = $environmentService;
}
public function index()
{
// 获取环境信息
$environment = $this->environmentService->current();
$isLocal = $this->environmentService->isLocal();
$config = $this->environmentService->getConfig();
return view('home', compact('environment', 'isLocal', 'config'));
}
}
创建环境中间件
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class EnvironmentMiddleware
{
/**
* 允许访问的环境
*/
protected $allowedEnvironments = ['local', 'staging'];
/**
* 处理请求
*/
public function handle(Request $request, Closure $next, ...$environments)
{
// 检查环境
if (app()->environment('production') && !$this->isAllowedEnvironment()) {
abort(403, '禁止访问');
}
// 添加环境信息到请求
$request->attributes->set('environment', app()->environment());
return $next($request);
}
protected function isAllowedEnvironment(): bool
{
return in_array(app()->environment(), $this->allowedEnvironments);
}
}
环境配置示例
bootstrap/app.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
)
->withMiddleware(function (Middleware $middleware) {
// 注册环境中间件
$middleware->alias([
'environment' => \App\Http\Middleware\EnvironmentMiddleware::class,
]);
})
->create();
.env 文件
APP_NAME=Laravel APP_ENV=local # 或 production, staging, testing APP_DEBUG=true # 生产环境设置为 false APP_URL=http://localhost
config/app.php
<?php
return [
'name' => env('APP_NAME', 'Laravel'),
'env' => env('APP_ENV', 'production'),
'debug' => (bool) env('APP_DEBUG', false),
// 其他配置...
];
Blade 模板中使用
{{-- 直接判断环境 --}}
@if(app()->environment('local'))
<p>当前为本地环境</p>
@endif
{{-- 显示调试信息 --}}
@if(config('app.debug'))
<p>调试模式已开启</p>
@endif
{{-- 加载不同资源 --}}
@if(app()->environment('production'))
<script src="{{ mix('js/app.production.js') }}"></script>
@else
<script src="http://localhost:3000/js/app.js"></script>
@endif
依赖注入方式
// 在任何类中通过构造函数注入
use Illuminate\Contracts\Foundation\Application;
class AnyService
{
protected $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function checkEnvironment(): string
{
return $this->app->environment();
}
}
常见环境配置
// 根据环境条件执行不同逻辑
if (app()->environment('local')) {
// 本地环境配置
config(['database.connections.mysql.host' => '127.0.0.1']);
} elseif (app()->environment('staging')) {
// 预发布环境配置
} elseif (app()->environment('production')) {
// 生产环境配置
$this->app->make(\Illuminate\Contracts\Http\Kernel::class)->bootstrap();
}
// 获取服务器相关信息
$server = $_SERVER;
$serverEnvironment = $server['SERVER_NAME'] ?? '';
使用这些方法,你可以灵活地获取和检测 Laravel 应用的环境信息,从而根据不同的环境做出相应的处理。