Search code examples
phpenvironment-variablesslimphpactiverecord

How to use environment variable effectively


So I use two main libraries for PHP project right now: php-activerecord and slim micro framework. I am also a user of vagrant and puppet cause I like keeping thing in sync. The one thing with this that I cannot seem to wrap my head around at this point is managing the different environments that my code goes to. It seems that the two libraries I mention attempt to give a mechanism to mange this but I am not seeing where I should put this kind of information.

//This is the config for php-AR
ActiveRecord\Config::initialize(function($cfg){
    $cfg->set_model_directory('models');
    $cfg->set_connections(array(
        //This is what I am interested in
        'development' => 'mysql://username:password@localhost/database_name'));
});

Similar to the above Slim has environments settings as well. Are these environment settings all based off of a config file that just ifs its way through based on the $_SERVER super global?

How is this normally managed? I am mostly curious for larger environments.

Edit 1) Just to be a bit more clear. I am curious about the logic added to code and setting within servers that are used. I know that is a bit broad so see below.

I have seen a lot of uses where .htaccess is mentioned to pull environment variables from. Obviously as I mentioned PHP has the $_SERVER super global that I can build logic around. Thanks to Diederik I now know I can use ~/.bash_profile on my servers.


Solution

  • Have you looked at the readme for ActiveRecord? It clearly states how to achieve this. In the code you posted above you already define a development database. You can simple add new ones to that as much as you want. The only bit you'll have to change once you upload to a different server is this part:

    ActiveRecord\Config::initialize(function($cfg)
    {
      $cfg->set_default_connection(your_environment);
    });
    

    Now, your_environment needs to be defined first. This can be achieved by doing something like:

    $cfg->set_default_connection(getenv('APP_ENV'));
    

    And then you'll just have to define that environment variable. This can be done through multiple ways. An example is to put the following in your ~/.bash_profile:

    export APP_ENV="development"
    

    That should do it.