我在哪里放置全局变量在 Yii2 类似于 YII_DEBUG 和 YII_ENV [英] Where do I put global Variables in Yii2 similar to YII_DEBUG and YII_ENV
问题描述
我正在构建一个网站,该网站有一个名为市场"的子域".所以网址将是marketplace.sample.com.我正在使用 Yii2 高级应用程序,并将以下代码添加到位于前端/网络的 index.php 中.
I'm building a website that has a "subdomain" called marketplace. so the url will be marketplace.sample.com. I'm using the Yii2 advanced application and I added the following code to my index.php located in frontend/web.
defined('MARKETPLACE') or define('MARKETPLACE', preg_match('/^marketplace/', $_SERVER['HTTP_HOST']) === 1 ? true : false);
这适用于我的环境,但是,我刚刚意识到 index.php 文件在 Yii2 的 .gitignore 文件中,因为该文件是由 init 脚本创建的,因此运行 init 将覆盖对其的更改.
This works on my environment, however, I just realized that the index.php file is in the .gitignore file in Yii2 because that file is created by the init script and so changes to it will be overwritten by running the init.
无论如何,问题是:我应该把这段代码放在哪里,以便它可以提交并与开发团队的其他成员共享,并在代码推送时将其投入生产?
Anyway, so the question is: Where do I put this code so that it can be committed and shared with the rest of the dev team and make it to production when the code is pushed?
我尝试将此代码放在 common/config/params.php 中,但是当我尝试访问该变量以确定要使用的路由时,我不能,因为在前端/配置时尚未初始化 Yii 应用程序/main.php 文件运行时,我收到一个错误,提示我正在尝试访问非对象的属性.
I tried to put this code in the common/config/params.php but then when I try to access the variable to determine which route to use I can't because the Yii app has not be initialized when the frontend/config/main.php file is run and I get an error that I am trying to access a property of a non-object.
/frontend/config/main.php
/frontend/config/main.php
'defaultRoute' => MARKETPLACE ? 'marketplace' : 'site',
/frontend/config/main.php(用参数代替)
/frontend/config/main.php (with param instead)
'defaultRoute' => Yii::$app->params['marketplace'] ? 'marketplace' : 'site'
第二个给出了我试图访问非对象的属性的错误.
this second one gives the error that I am trying to access a property of a non-object.
推荐答案
在目录中:
common/config
您可以使用 bootstrap.php 文件插入您需要的代码.此文件在启动阶段执行,在 .gitignore 中未指明.
you can use bootstrap.php file for inserting the code you need. This file is executed in startup phase and is not indicated in .gitignore.
这样你就可以在使用 GIT 时分配常量 MARKETPLACE 确保传播代码
In this way you can assign the constant MARKETPLACE sure of propagate the code when you use the GIT
这篇关于我在哪里放置全局变量在 Yii2 类似于 YII_DEBUG 和 YII_ENV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!