Yii2:配置参数与常量 [英] Yii2: Config params vs. constants

查看:413
本文介绍了Yii2:配置参数与常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候应该使用什么?



我可以在index.php条目脚本文件中定义常量,像在 Yii2 guide:constants 。或者,我可以使用配置中的参数 - 在 YII2指南中解释: params



目前在我看来,如果我想合并这样的值,params有点不太舒服:

  define('SOME_URL','http://some.url'); 
define('SOME_SPECIALIZED_URL',SOME_URL。'/ specialized');此外,访问是更多的代码( Yii :: $ app->



<



那么,什么时候应该或者可以使用什么?

解决方案

我倾向于使用Yii应用程序参数。这样做的主要原因是这些类型的参数中的值会根据代码运行的环境而改变。所以我将有一个运行的构建系统(我使用 Phing ),并从非版本控制文件(如build.properties)中提取设置。



任何dev数据库设置,dev域设置,api沙箱地址等将被加载到我的开发环境中,并且当在现场服务器上运行构建时将使用正确的生产值。



如果你在某些类型的php文件中设置这些值,那么使用版本控制进行跟踪会变得有问题,因为每次在dev环境中构建时,都会对index.php文件进行更改。有人甚至可能最终会错误地提交这些更改。



因此,总而言之,我会说如果他们是真正的常数 - 在代码运行的任何环境 - 他们可能是一个常数是罚款。如果这些值可能改变,取决于代码运行的位置,那么我的首选项是将它们放在params中,并让您的构建系统从非版本控制的文件加载它们。


When should I use what?

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');

Besides, accessing is bit more code (Yii::$app->params['something']) compared to constants.

So when should or could I use what?

解决方案

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.

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.

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:配置参数与常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆