Introduction ¶
Using this you can predefine configurations for use in different environments, like development, testing, staging and production.
The main config (main.php
) is extended to include the Yii paths and debug flags.
There are mode_<environment>.php
files for overriding and extending main.php for specific environments.
Additionally, you can overrride the resulting config by using a local.php
config, to make
changes that will only apply to your specific installation.
This class was designed to have minimal impact on the default Yii generated files. Minimal changes to the index/bootstrap and existing config files are needed.
The Environment is determined with PHP's getenv(), which searches $_SERVER
and $_ENV
.
There are multiple ways to set the environment depending on your preference.
Setting the environment variable is trivial on both Windows and Linux, instructions included.
You can optionally override the environment by creating a mode.php
in the config directory.
If you want to customize this class or its config and modes, extend it! (see ExampleEnvironment.php)
Resources ¶
All information is available within the GitHub-project:
- Project Home
- Readme / Requirements / Installation / Usage
- Downloads (no new downloads on yiiframework.com)
- Issues
Feature request: integrate console application config
I received a feature request, to expand my extension to integrate console application configurations.
Are more of you interested? (you can indicate so by up-voting this post for example)
Cannot autoload model and component classes
Ok, I can autoload them but not in the way I want.
If I include:
'import' => array( 'application.models.*', 'application.components.*', ),
in the main.php file then my controllers DO NOT load. I get:
include(Controller.php): failed to open stream: No such file or directory
BUT, if i include them in the config array of mode_development (for example) then they work fine.
I guess this has to do with the paths somehow but I just can't find out how/why/where!
Although, not a show stopper, it is quite a drag to include common configuration settings to ALL my mode_* config files, when the correct way would be to include them in the main.php (once)
Thanks...
Re: Cannot autoload model and component classes
I'm using imports in both my main.php and my mode_*.php, and they are merged without problems.
You can use $env->getDebug() to see the generated merged config, I guess you maybe just misplaced one array part?
console app
I'd very much like to see this work for console app. My client is using your Environment in their application, I can't see to access $environment or even Yii::app() from within the CConsole child though.
Support for console applications
I'm also interested in support for console applications
I'v have two applications that have both web and console components and i would like to be able to use different configuration files for diferent environments.
Environment class with console support
See: https://github.com/janisto/yii-environment
Console
Thanks i'll take a look and get back to you.
@console applications
Janisto's version looks ok, but I'm not sure I like copying most of the configuration twice, while the difference between web and console is usually just unsetting certain components.
Including support for yiilite is a good idea.
I'll see about doing some work on my version soon.
@marcovtwout
Typically I only have "web" config, but when I have "web" and "console" config, I only need to have very simple configuration for console. Usually just importing models and then use cache, db, log and minimal params, but my "web" config has a lot of configurations, components, modules and params.
I was thinking about using "common" array and then merge "web" and "console" arrays to that, but that would create unnecessary complexity if one would only use "web" config.
In the end I preferred to copy-paste those couple of configurations to "console" for the sake of simplicity and clean console configuration.
New version with console application support
I figured out a way to have the best of both worlds. The console config is created seperately in the key configConsole. If for example you want to share db and params from configWeb, set the array value to 'inherit'. This way we have maximum flexibiliy and no redundant code.
Determining the environment was a bit more tricky. Console apps use php-cli and not Apache, so I couldn't directly call the SetEnv var. Therefore the environment is read from a file which is generated by running the Webapp. In case you only have a console app, you can create the file yourself.
I didn't add yiiLite as a separate property because you can simply set the yiiPath to yiilite if you wish.
Thank you everyone for the input, enjoy the new addition, and please give your feedback :)
Re: New version with console application support
When you execute a PHP script from the command line, it inherits the environment variables defined in your shell.
That means you can set an environment variable using the export command like so:
export YII_ENVIRONMENT='TEST'
Re: Re: New version with console application support
We can discuss this issue here: http://code.google.com/p/yii-environment/issues/detail?id=1
nginx configuration (environment variable)
Hi,
I use nginx as webserver and there I configured it like the following:
[bash] ... location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; fastcgi_index index.php; fastcgi_param YII_ENVIRONMENT "development"; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } ...
Re: Re: Re: New version with console application support
Latest development version uses getenv() for a more robust way of supporting both webapps and consoleapps.
Take a look here: http://code.google.com/p/yii-environment/source/detail?r=59
mode.php
Can we please have mode.php back as a local environment override option? Setting global env variable affects all console applications on given machine. For example, some of my web sites are running background tasks as a console application cron jobs. At the same time, I do unit testing of sites about to be launched. That gets even more complicated on shared hostings, where you may have possibility to set shell env, but can't influence environment in which httpd lives... That should be as simple as checking if mode.php exist before attempting to use getenv(). Ideally if mode.php worked for both console and web apps.
Re: mode.php
I also think (temporary) running more than one environment on one server is a common case.
Having mode.php as an optional override is an acceptable solution.
I will briefly check if the performance overhead is negligible, and probably implement it soon.
Superb
Very good extension!
Console [SOLVED}
Hi.
How to use it with yiic?
Thank you.
[SOLVED]
Had to modify yiic.php like this:
<?php // set environment require_once(dirname(__FILE__) . '/extensions/yii-environment/Environment.php'); $env = new Environment(); //$env = new Environment('PRODUCTION'); //override mode // set debug and trace level defined('YII_DEBUG') or define('YII_DEBUG', $env->yiiDebug); defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', $env->yiiTraceLevel); // run Yii app //$env->showDebug(); // show produced environment configuration $env->runYiiStatics(); $config=$env->configConsole; require_once($env->yiicPath); ?>
runYiiStatics not working
First of all: A real great extension!!! But I am having a problem with it :(
I defined that in my main.php
'yiiSetPathOfAlias' => array( 'xupload' => realpath(dirname(__FILE__) . '/../extensions/Xupload'), ),
In your Environment this is pocessed on line 374 and I am getting an error there:
PHP Fatal error: Class 'Yii' not found in ... on line 374
I guess the autoloading mechanism is not present at this point or why I am getting this error?
Btw: I am in console mode; for normal webapp everything is fine!
Re: runYiiStatics not working
Read the comment here: example yiic.php
runYiiStatics not working
Thanks a lot!! I didn't see this comment before :(
do you continue developing at github.com?
Hi,
do you plan to continue developing at https://github.com/janisto/yii-environment ?
Re: do you continue developing at github.com?
The GitHub url you are mentioning is someone else's fork.
I am using Google Code to develop code and track bugs: http://code.google.com/p/yii-environment/
Re: do you continue developing at github.com?
Hi kmindi,
that's my fork of yii-environment. Feel free to add feature request issues there, too :)
Regarding Yii versions
I'm using it on multiple sites with 1.1.11
CClientScript not found [SOLVE]
Great extension!!! But I am having some problem with it,
I get this error when I defined the coreScriptPotision in my main.php
Fatal error: Class 'CClientScript' not found in C:\xampp\htdocs\yii-locations\protected\config\main.php on line 78
'clientScript' => array( 'coreScriptPosition'=>CClientScript::POS_END, )},
Any help??
Re: CClientScript not found
Because the Yii path is part of the environment configuration, it is included in that specific config file. That means that the Yii core classes will be included AFTER the configuration file has been parsed. Which means CClientScript does not yet exist when you create the configuration. This is a limitation of the current implementation.
In your case, I would simply solve it like this:
'clientScript' => array( 'coreScriptPosition'=>2, //CClientScript::POS_END in Yii 1.x )},
Thanks for the great extension!
I was a little leery about undertaking this one as I'm still new to Yii AND Git, but it worked out great with very little effort. Using this extension in conjunction with git, i can deploy through QA and Prod with a couple clicks each. This functionality should definitely be part of the core.
For anyone curious, here is the article I used to set up my deployments:
http://toroid.org/ams/git-website-howto
I'm using NetBeans with the built-in git module, and it is literally save, commit, push to a live site.
Thabks
Very helpfull extension
Question to test environment and local.php
First of all I want to point out that this is a great extension and also the documentation is very detailed and useful.
To my question:
I'm currently setting up this extension as it is recommended in the WIKI. Nevertheless I have the following situation: I use the file 'local.php' to run the application on my local machine, but unfortunately this makes testing on this machine impossible, because the config in 'local.php' overrides the test config.
How could I manage to use a 'local.php' file to run it on my local machine AND also test on my local machine?
Did I miss something?
Thx in advance :)
Re: Question to test environment and local.php
Thanks for your feedback :)
If your local.php sets parameters that you don't want to use with mode_test.php, you could:
Re: Re: Question to test environment and local.php
Thx for the fast response! I did as you said and extended the Environment.php file to serve an environment 'mode_development_local'. Furthermore I will exclude this file from my repository, so that everybody can configure this file on his own!
Thx again :)
Prevent Problems with local.php
To prevent problems with a mistake upload of local.php to the server,
I added in beginning of the file:
if($_SERVER['HTTP_HOST'] != 'domain.local') return array();
But I think it needs another method to include a local file, something like - include a file with current domain:
domain.php
:$fileLocalConfig = $this->getConfigDir().$_SERVER['HTTP_HOST'].'.php'; if (file_exists($fileLocalConfig )) {...
Re: Prevent Problems with local.php
You won't accidentally upload the file if you're using a versioning system like SVN or Git, and this will be true for most people. If you're updating your website just with FTP, you got more problems to worry about ;)
For edge cases like your suggestion, feel free to extend the class and customize it for your own use. ;)
Re: Re: Prevent Problems with local.php
You are right (I use sftp only between the local dev and remote dev), But you don't think it's more convenient to use a config file per domain, dev.domain, test.domain, domain.local and etc...?
(instead of using 'Environment Variables'...)
Re: Re: Re: Prevent Problems with local.php
If I understand correctly, you would change the name of the config file depending on the domain set in the webserver? By setting an environment variable, you only have to do this once no matter how many applications you have installed. Also, determining domain would only work combined with the web server, but this extension is also fit for command line use. Suggestions are always welcome though! :)
Determining environment based on domain name
@MatiH
You could easily set correct environment in a .htaccess file. Example:
~~~
RewriteRule ^ - [E=YII_ENVIRONMENT:PRODUCTION]
RewriteCond %{SERVER_NAME} ^local-. [OR]
RewriteCond %{SERVER_NAME} ^dev..
RewriteRule ^ - [E=YII_ENVIRONMENT:DEVELOPMENT]
~~~
Above snippet will set YII_ENVIRONMENT to PRODUCTION by default and to DEVELOPMENT when server name begins with 'local-' or 'dev.'
Thanks + a suggestion
Many thanks for this extension (thumbs up)!
On the subject:
Because the Yii path is part of the environment configuration, it is included in that specific config file. That means that the Yii core classes will be included AFTER the configuration file has been parsed. Which means CClientScript does not yet exist when you create the configuration. This is a limitation of the current implementation.
what would you think of the following approach (any drawbacks?):
config/main.php
stays the same (andmode_development.php
,mode_production.php
etc. respectively).'yiiPath', 'yiiDebug'
etc) go into a separate fileenv.php
(andenv_development.php
,env_production.php
etc. respectively).Environment
gets a new function:getEnvConfig
(similar togetConfig
)setEnvironment
becomes:$config = $this->getEnvConfig(); $this->yiiPath = $config['yiiPath']; if (isset($config['yiicPath'])) $this->yiicPath = $config['yiicPath']; if (isset($config['yiitPath'])) $this->yiitPath = $config['yiitPath']; $this->yiiDebug = $config['yiiDebug']; $this->yiiTraceLevel = $config['yiiTraceLevel']; require_once($this->yiiPath); // <---- Here we include the Yii core class $this->configWeb = $this->getConfig(); $this->configWeb['params']['environment'] = strtolower($this->mode); $this->configConsole = $this->getConsoleConfig(); if(!empty($this->configConsole)) { $this->processInherits($this->configConsole); // Process configConsole for inherits $this->configConsole['params']['environment'] = strtolower($this->mode); } $this->yiiSetPathOfAlias = $env_config['yiiSetPathOfAlias'];
Re: Thanks + a suggestion
First of all, thanks for your feedback. :)
Your suggestion would certainly work for what you want to achieve. My personal preference: I like having just one file per environment which contains all needed configuration. It keeps it straightforward (prevent naming ambiguity, what does envConfig mean versus config?). In case I need to use a Yii class constant in one of my configuration files, I simply copy it's value and comment the const name, which is acceptable for me (example in comment "Re: CClientScript not found").
for those who want to use as submodule
I found a git repo which is up to date (currently) https://github.com/flamusdiu/yii-environment
I would definetly like the original author to put the code himself in a puplicly available git repository (for example github ;)).
Re: for those who want to use as submodule
What do you mean with submodule?
The code for this extension is available on Google Code, links are in the description.
Whats the benefit of a git submodule
First: I use git for version control (which is superior to svn in most use cases)
Second: A git submodule is a seperate repository within a "parent"-git repository. It tracks the changes by itself. Wheras the "parent" repository only stores the id of the commit of the submodules.
The benefit of this is, that I/one does not have to track the changes in my own repositories, which would be redundant, because the code is already tracked in your/the repository of that library/plugin/tool/extension.
Therefore I recommend you switch from svn to git (which provides linear history just like svn does).
Re: Whats the benefit of a git submodule
I use both, but in my environment Subversion is still used most. Thank you for explaining the extra benefits, I will consider moving my google code projects to github.
Local test file
Hey guys,
what do you think is the best way to have a local test configuration. I already created a local development file, which works without problems. But for testing, i need to specify a different database and I cannot use mode_test.php since that file is for the test system.
Thx in advance :)
New release
I updated the extension with simplified alias creation without using runYiiStatics(). This also means you don't have to copy/include yiic from the framework any more. :)
How to run from console
Hi,
Great extension. How do I run console apps using the extension?
Thanks!
RE: How to run from console
Hey LittleBob,
Here in order for me to set up my app to use environments in console I followed the instructions here: http://code.google.com/p/yii-environment/wiki/EnvironmentClass under Setting Environment > Linux and had to set that up for the user who was running the cron job.
Then I had to update my configuration files for the configConsole as that was added in the changelog in V 2.0. The site I linked to up there also should be enough to get you all set there.
Project moved to GitHub
I moved the project from google code to GitHub, and decided to keep all documentation there. :) See updates description above.
Install through Composer
Since version 5, the preferred installation method is through Composer. See updates instructions https://github.com/marcovtwout/yii-environment/blob/master/README.md
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.