问题描述
我什么时候应该使用什么?
When should I use what?
我可以选择在index.php入口脚本文件中定义常量,就像在。或者,我可以在配置中使用这些参数-在。
I have the option to define constants in the index.php entry script file like it is recommended in Yii2 guide: constants. Or I could use the params in the configuration - explained in YII2 guide: params. Both are per application and not really global.
当前,在我看来,如果我想像这样组合值,则参数不太舒服:
Currently, it seems to me that params are a bit less comfortable if I want to combine values like this:
define('SOME_URL', 'http://some.url');
define('SOME_SPECIALIZED_URL', SOME_URL . '/specialized');
此外,访问还有更多代码( Yii :: $ app-> ; params ['something']
)与常量进行比较。
Besides, accessing is bit more code (Yii::$app->params['something']
) compared to constants.
那么我什么时候应该或可以使用什么呢?
So when should or could I use what?
小更新:在PHP 7中, define()
也支持数组,因此可以配置整个params结构作为一个常数。
Small update: in PHP 7 define()
supports arrays as well, so the whole params structure can be configured as a constant. Probably better supported by IDEs.
推荐答案
我倾向于使用Yii应用程序参数。造成这种情况的主要原因是,这些类型的参数中保存的值往往会根据运行代码的环境而变化。因此,我将运行一个构建系统(我使用),并从非版本控制文件(例如build.properties)中提取设置。
I tend to use the Yii application parameters. The main reason for this is the values held in these kind of parameters tend to change depending on the environment that the code is run in. So I will have a build system that runs (I use Phing) and pulls in settings from a non-version controlled file such as build.properties.
因此任何开发数据库设置,开发域设置,api沙箱地址等都将加载到我的开发环境中,并且在实时服务器上运行构建时将使用正确的生产值。
So any dev database settings, dev domain settings, api sandbox addresses etc will be loaded in in my development environment and the correct production values will be used when a build is run on a live server.
如果您要在某种php文件中设置这些值,那么使用版本控制进行跟踪就成为问题,因为每次在开发环境中进行构建时,都会对index.php文件进行更改。
If you were settings these values in some kind of php file, then tracking with version control becomes problematic because each time you build in your dev environment changes would be made to your index.php file. Someone might even end up committing these changes in by mistake.
因此,总而言之,我想说它们是否是真正的常数,在运行代码的任何环境中都是相同的-也许常数就可以了。如果这些值可能改变,具体取决于代码在何处运行,那么我的首选是将它们放在参数中,并让您的构建系统从非版本控制文件中加载它们。
So in summary, I would say if they are true constants - the same in any environment in which the code runs - they maybe a constant is fine. If these values might change, depending on where the code is run, then my preference is to place them in params and let your build system load them from a non-version controlled file.
这篇关于Yii2:配置参数与const / define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!