liftkit/environment-detection

一个用于定义和检测执行环境的库

v1.0.3 2018-01-29 15:03 UTC

This package is auto-updated.

Last update: 2024-09-12 01:40:12 UTC


README

一个简单的库,用于检测当前应用程序正在执行的执行环境。

创建一个新的检测器

use LiftKit\EnvironmentDetection\Detector;

$detector = new Detector;

匹配 HTTP_HOST

匹配的值是 $_SERVER['HTTP_HOST']。这个值是从 web 服务器传递给 php 的,作为请求发送到的域名。

$detector->ifHttpHost('something.localhost', 'local')
	->ifHttpHost('test.something.com', 'test')
	->ifHttpHost('www.something.com', 'production')
	->ifHttpHost('*.something.com', 'subdomain')
	->ifHttpHost('*', 'default'); // if no other pattern matches
	
$environment = $detector->resolve();

$environment 将等于 'development''test''production'subdomaindefault 中的一个,具体取决于应用程序访问的宿主。请注意,如果应用程序是通过 CLI 访问的,则 $_SERVER 不会被填充。这些都不会通过,且 $detector->resolve() 将返回 null

匹配当前机器的主机名

这测试命令 uname -n(或等效的 php_uname('n'))的输出。

$detector->clear() // clear previous rules
	->ifHostName('*.local', 'local') // default pattern for macOS
	->ifHostName('*', 'default'); // will match all others

$environment = $detector->resolve();

匹配环境变量

这个测试针对 $_ENV 中的一个变量。

$detector->clear() // clear previous rules
	->ifEnv('environment', 'dev', 'local') // tests $_ENV['development'] == 'dev'
	->ifEnv('environment', '*', 'default'); // will match all values of $_ENV['environment'], if $_ENV['environment'] is defined

$environment = $detector->resolve();

匹配任意值

$detector->clear() // clear previous rules
	->ifMatch(php_uname('s'), 'Darwin', 'mac') // if macOS
	->ifMatch(php_uname('s'), 'Linux', 'linux'); // if Linux

$environment = $detector->resolve();

注意 php_uname('s') 报告的是操作系统内核的名称。

匹配布尔表达式和默认值

$detector->clear() // clear previous rules
	->ifBool(defined('TEST_ENVIRONMENT'), 'test')
	->defaultTo('production'); // default value

$environment = $detector->resolve();

您也可以混合使用条件

$detector->clear() // clear previous rules
	->ifMatch(php_sapi_name(), 'cli', 'cli') // in CLI
	->defaultTo('web'); // otherwise assume web request

$environment = $detector->resolve();

没有匹配

如果没有默认值且没有条件匹配,则 $detector->resolve() 将返回 null

$detector->clear(); // clear previous rules

$environment = $detector->resolve(); // $environment === null