찾다
백엔드 개발PHP 튜토리얼Lumen/Laravel .env 파일의 환경 변수의 효율성에 대해 토론합니다.

 .env 파일은 다른 유효한 환경 변수로 사용자 정의할 수 있으며 변수는 env() 또는 $_SERVER 또는 $_ENV을 호출하여 얻을 수 있습니다. 그렇다면 env()는 이러한 변수에 어떻게 로드됩니까? Lumen의 Vendor/laravel/lumen-framework/src/helpers.php에서 env 함수가 다음과 같이 정의되어 있음을 확인할 수 있습니다.

if (! function_exists('env')) {/**
     * Gets the value of an environment variable. Supports boolean, empty and null.
     *
     * @param  string  $key
     * @param  mixed   $default
     * @return mixed     */function env($key, $default = null)
    {$value = getenv($key);if ($value === false) {return value($default);
        }switch (strtolower($value)) {case 'true':case '(true)':return true;case 'false':case '(false)':return false;case 'empty':case '(empty)':return '';case 'null':case '(null)':return;
        }if (Str::startsWith($value, '"') && Str::endsWith($value, '"')) {return substr($value, 1, -1);
        }return $value;
    }
}

env 함수에서 환경을 읽기 위해 getenv()가 호출되는 것을 볼 수 있습니다. 변수. getenv()는 $_SERVER 또는 $_ENV 전역 변수를 읽기 위해 PHP가 기본적으로 제공하는 함수 API라는 것도 알고 있습니다. 왜 .env 파일의 환경 변수를 getenv()를 통해 얻을 수 있나요? vlucas/phpdotenv는 Lumen 또는 Laravel 공급업체에서 찾을 수 있습니다. 별도로 다운로드하려면 여기로 이동하세요.

vlucas/phpdotenv/src/Loader.php 파일에서 .env가 배열에 로드된 다음 각 줄이 setter로 처리되고 setEnvironmentVariable() 메서드가 호출되는 것을 볼 수 있습니다.

/**
     * Load `.env` file in given directory.
     *
     * @return array     */public function load()
    {$this->ensureFileIsReadable();$filePath = $this->filePath;$lines = $this->readLinesFromFile($filePath);foreach ($lines as $line) {if (!$this->isComment($line) && $this->looksLikeSetter($line)) {$this->setEnvironmentVariable($line);}
        }return $lines;
    }/**
     * Read lines from the file, auto detecting line endings.
     *
     * @param string $filePath
     *
     * @return array     */protected function readLinesFromFile($filePath)
    {// Read file into an array of lines with auto-detected line endings$autodetect = ini_get('auto_detect_line_endings');ini_set('auto_detect_line_endings', '1');$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);ini_set('auto_detect_line_endings', $autodetect);return $lines;
    }

Loader::setEnvironmentVariable($name, $value = null)은 다음과 같이 정의됩니다.

/**
     * Set an environment variable.
     *
     * This is done using:
     * - putenv,
     * - $_ENV,
     * - $_SERVER.
     *
     * The environment variable value is stripped of single and double quotes.
     *
     * @param string      $name
     * @param string|null $value
     *
     * @return void     */public function setEnvironmentVariable($name, $value = null)
    {list($name, $value) = $this->normaliseEnvironmentVariable($name, $value);// Don't overwrite existing environment variables if we're immutable
        // Ruby's dotenv does this with `ENV[key] ||= value`.if ($this->immutable && $this->getEnvironmentVariable($name) !== null) {return;
        }// If PHP is running as an Apache module and an existing
        // Apache environment variable exists, overwrite itif (function_exists('apache_getenv') && function_exists('apache_setenv') && apache_getenv($name)) {
            apache_setenv($name, $value);
        }

        if (function_exists('putenv')) {
            putenv("$name=$value");
        }

        $_ENV[$name] = $value;
        $_SERVER[$name] = $value;}

  PHP tenv 그녀는 누구입니까?

Loads environment variables from .env to getenv(), $_ENV and $_SERVER automagically.

This is a PHP version of the original Ruby dotenv.

 왜 .env인가요?

You should never store sensitive credentials in your code. Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environments – such as database credentials or credentials for 3rd party services – should be extracted from the code into environment variables.

Basically, a .env file is an easy way to load custom configuration variables that your application needs without having to modify .htaccess files or Apache/nginx virtual hosts. This means you won't have to edit any files outside the project, and all the environment variables are always set no matter how you run your project - Apache, Nginx, CLI, and even PHP 5.4's built-in webserver. It's WAY easier than all the other ways you know of to set environment variables, and you're going to love it.

. NO editing virtual hosts in Apache or Nginx
. NO adding php_value flags to .htaccess files
. EASY portability and sharing of required ENV values
. COMPATIBLE with PHP's built-in web server and CLI runner

위 내용은 Lumen/Laravel .env 파일의 환경 변수의 효율성에 대해 토론합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
교통량이 많은 웹 사이트를위한 PHP 성능 튜닝교통량이 많은 웹 사이트를위한 PHP 성능 튜닝May 14, 2025 am 12:13 AM

thesecrettokeepingAphp-poweredwebsiterunningsmoothlydlyUnderHeavyloadInvolvesEveralKeyStrategies : 1) ubstractOpCodeCachingWithOpCacheTecescripteExecutionTime, 2) usedatabasequeryCachingwithRedSendatabaseload, 3) LeverAgeCdnslikeCloudforforporerververforporporpin

PHP의 종속성 주입 : 초보자를위한 코드 예제PHP의 종속성 주입 : 초보자를위한 코드 예제May 14, 2025 am 12:08 AM

Code는 코드가 더 명확하고 유지 관리하기 쉽기 때문에 의존성 주입 (DI)에 관심을 가져야합니다. 1) DI는 클래스를 분리하여 더 모듈 식으로 만들고, 2) 테스트 및 코드 유연성의 편의성을 향상시키고, 3) DI 컨테이너를 사용하여 복잡한 종속성을 관리하지만 성능 영향 및 순환 종속성에주의를 기울이십시오. 4) 모범 사례는 추상 인터페이스에 의존하여 느슨한 커플 링을 달성하는 것입니다.

PHP 성능 : 응용 프로그램을 최적화 할 수 있습니까?PHP 성능 : 응용 프로그램을 최적화 할 수 있습니까?May 14, 2025 am 12:04 AM

예, PPAPPLICATIONISPOSSIBLEADESLESTION.1) INVERECINGUSINGAPCUTERODUCEDABASELOAD.2) INCODINCEDEXING, ENGICIONEQUERIES 및 CONNECTIONPOULING.3) 향상된 보드 바이어링, 플로 팅 포르코 잉을 피하는 최적화 된 APPCUTERODECEDATABASELOAD.2)

PHP 성능 최적화 : 궁극적 인 가이드PHP 성능 최적화 : 궁극적 인 가이드May 14, 2025 am 12:02 AM

theKeyStrategiesToSINCINTIFILINTINTIFILINTINTHPPORMATIONPERFORMANCEARE : 1) USEOPCODECACHING-CCHACHETEDECUTECUTINGTIME, 2) 최적화 된 ABESINSTEMENTEMENDSTEMENTEMENDSENDSTATEMENTENDS 및 PROPERINDEXING, 3) ConfigureWebSerVERSLIKENGINXXWITHPMFORBETPERMERCORMANCES, 4)

PHP 의존성 주입 컨테이너 : 빠른 시작PHP 의존성 주입 컨테이너 : 빠른 시작May 13, 2025 am 12:11 AM

aphpdectionenceindectioncontainerisatoolthatmanagesclassdependencies, 향상 Codemodularity, testability 및 maintainability.itactAsacentralHubForCreatingAndingDinjectingDingingDingingdecting.

PHP의 종속성 주입 대 서비스 로케이터PHP의 종속성 주입 대 서비스 로케이터May 13, 2025 am 12:10 AM

대규모 응용 프로그램의 경우 SELLENCIONINGESS (DI)를 선택하십시오. ServicElocator는 소규모 프로젝트 또는 프로토 타입에 적합합니다. 1) DI는 생성자 주입을 통한 코드의 테스트 가능성과 모듈성을 향상시킵니다. 2) Servicelocator는 센터 등록을 통해 서비스를 얻습니다. 이는 편리하지만 코드 커플 링이 증가 할 수 있습니다.

PHP 성능 최적화 전략.PHP 성능 최적화 전략.May 13, 2025 am 12:06 AM

phPapplicationSCanBeoptimizedForsPeedandefficiencyby : 1) ENABLEOPCACHEINPHP.INI, 2) PREPAREDSTATEMENTSWITHPDOFORDATABASEQUERIES 사용

PHP 이메일 검증 : 이메일이 올바르게 전송되도록합니다PHP 이메일 검증 : 이메일이 올바르게 전송되도록합니다May 13, 2025 am 12:06 AM

phpeMailValidationInvoLvestHreesteps : 1) formatValidationUsingRegularexpressionsTochemailformat; 2) dnsValidationToErethedomainHasaValidMxRecord; 3) smtpvalidation, theSTHOROUGHMETHOD, theCheckSiftheCefTHECCECKSOCCONNECTERTETETETETETETWERTETWERTETWER

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.