PSR-1:2.3。副作用:配置文件中的变量

问题描述 投票:0回答:1

[PSR-1包括推荐2.3. Side Effects

文件应该声明新的符号(类,函数,常量等),并且不会引起其他副作用,或者应该执行具有副作用的逻辑,但不应两者都做。

考虑这个示例(我自己)在config.php文件中:

/**
 * Parsing the database URL.
 * DATABASE_URL is in the form:
 *  postgres://user:password@hostname:port/database
 * e.g.:
 *  postgres://u123:[email protected]:5432/dxyz
 */
$url = parse_url(getenv('DATABASE_URL'));
define('DB_HOST', $url['host']);
define('DB_NAME', substr($url['path'], 1)); // get rid of initial slash
define('DB_USER', $url['user']);
define('DB_PASSWORD', $url['pass']);

如果我这样做,实际上是在不遵守建议。 phpcs会因变量而抱怨:

FILE: config.php
-----------------------------------------------------------------------------------------------------------------
FOUND 0 ERRORS AND 1 WARNING AFFECTING 1 LINE
-----------------------------------------------------------------------------------------------------------------
 1 | WARNING | A file should declare new symbols (classes, functions, constants, etc.) and cause no other side
   |         | effects, or it should execute logic with side effects, but should not do both. The first symbol
   |         | is defined on line 17 and the first side effect is on line 162.
-----------------------------------------------------------------------------------------------------------------

替代方法是:

define('DB_HOST', parse_url(getenv('DATABASE_URL'))['host']);
define('DB_NAME', substr(parse_url(getenv('DATABASE_URL'))['path'], 1));
define('DB_USER', parse_url(getenv('DATABASE_URL'))['user']);
define('DB_PASSWORD', parse_url(getenv('DATABASE_URL'))['pass']);

没有变量,没问题。但这是WET,很难阅读。

我了解建议只是这样,它说的是“应该”,而不是“必须”。但这仍然困扰着我……一方面,任何时候我检查phpcs文件都会抱怨它,但每行只报告一次,这为添加更多在配置文件中没有位置的“副作用”敞开了大门。 >

我对整个PSR还是陌生的。

我想念任何巧妙的方法来摆脱变量,同时保持可读性吗?

一个必然结果是:那些坚持遵循信函建议的严肃项目如何处理?

[PSR-1包括建议2.3。副作用:文件应该声明新的符号(类,函数,常量等),并且不会引起其他副作用,或者文件应使用副作用...

php standards psr-1 php-fig
1个回答
0
投票

1。很好,不要流汗

© www.soinside.com 2019 - 2024. All rights reserved.