yatero/enivronment-picker

根据环境变量或URL选择标记环境。

v1.0.2 2019-03-15 14:44 UTC

This package is auto-updated.

Last update: 2024-09-16 03:26:20 UTC


README

此类允许您的应用程序根据以下内容确定正在运行的是哪个标记环境:

  • 环境变量(通过getenv()检测)
  • 传递给EnvironmentPicker::get()函数的URL
  • 当前URL(当不是通过CLI运行时)

使用方法

默认情况下,如果无法从环境变量或URL中确定环境,则类返回默认标记,即production

使用主机检测

请注意,当使用EnvironmentPicker::get()时,如果同时存在环境值和标记正则表达式,则始终优先考虑getenv()值。

$environments = array(
    'local'   => '/^(localhost(:{d}+)?)|(127\.0\.0\.1(:{d}+)?)$/i',
    'staging' => '/^(demo\.my-website\.com)|(8\.8\.8\.8)$/i'
);

// Initialize environments
\Yatero\EnvironmentPicker\EnvironmentPicker::init($environments);

// Returns the label of the environment for the current URL
\Yatero\EnvironmentPicker\EnvironmentPicker::get();


// Return the label of the environment for the given URL
\Yatero\EnvironmentPicker\EnvironmentPicker::get('https://demo.my-website.com/foo/bar');

使用预定义的环境值

您可以在服务器配置中设置环境变量,在您的<.htaccess>文件中(如果您正在使用Apache),或者在使用export ENGINE_ENV=staging时运行时。

请小心并事先初始化允许的环境。默认情况下,只有列表中的环境被允许作为值。如果您希望允许ENGINE_ENV接受任何值,则应调用EnvironmentPicker::strict(false)

$environments = array(
    'local'   => null,
    'staging' => null
);

// Initialize environments
\Yatero\EnvironmentPicker\EnvironmentPicker::init($environments);

// Before getting the current environment make sure that you have the right variable name
\Yatero\EnvironmentPicker\EnvironmentPicker::envVarKey('MY_VAR');

\Yatero\EnvironmentPicker\EnvironmentPicker::get();

您可以将标记正则表达式值作为回退,如果变量未设置或为空。

$environments = array(
    'local'   => '/^(localhost(:{d}+)?)|(127\.0\.0\.1(:{d}+)?)$/i',
    'staging' => '/^(demo\.my-website\.com)|(8\.8\.8\.8)$/i'
);

// Initialize environments
\Yatero\EnvironmentPicker\EnvironmentPicker::init($environments);

// Before getting the current environment make sure that you have the right variable name
\Yatero\EnvironmentPicker\EnvironmentPicker::envVarKey('MY_VAR');

\Yatero\EnvironmentPicker\EnvironmentPicker::get();