,host()
和httpHost()
>方法為URL操縱和域特異性邏輯提供了不同的功能。這在多租戶應用程序,跨域請求和動態URL生成方案中尤其有價值。 schemeAndHttpHost()
// Accessing host information $domain = $request->host(); // Returns the domain name $hostWithPort = $request->httpHost();// Includes the port if not standard (e.g., :8080) $fullHost = $request->schemeAndHttpHost();// Returns the full scheme and host (e.g., https://example.com)考慮多環境URL發電機服務的此示例:
>用法示例:
// app/Services/DomainRouter.php <?php namespace App\Services; use Illuminate\Http\Request; class DomainRouter { public function __construct(private Request $request) {} public function generateUrls(): array { $baseDomain = $this->request->host(); $fullSchemeHost = $this->request->schemeAndHttpHost(); return match ($this->detectEnvironment($baseDomain)) { 'production' => [ 'api' => "{$fullSchemeHost}/api/v1", 'web' => $this->request->httpHost(), 'assets' => str_replace('api', 'cdn', $fullSchemeHost), 'environment' => 'production' ], 'staging' => [ 'api' => "{$fullSchemeHost}/api/v1", 'web' => str_replace('api', 'staging', $this->request->httpHost()), 'assets' => str_replace('api', 'staging-cdn', $fullSchemeHost), 'environment' => 'staging' ], default => [ 'api' => 'http://localhost:8000/api/v1', 'web' => 'http://localhost:3000', 'assets' => 'http://localhost:9000', 'environment' => 'local' ] }; } private function detectEnvironment(string $host): string { if (str_contains($host, 'prod')) { return 'production'; } if (str_contains($host, 'staging')) { return 'staging'; } return 'local'; } }
> Laravel與主機相關的方法提供了一種靈活,有效的方法,用於在各種部署環境中管理特定領域的邏輯和URL生成。
以上是在Laravel管理請求主機信息的詳細內容。更多資訊請關注PHP中文網其他相關文章!