Mastering PHP Design Patterns
上QQ阅读APP看书,第一时间看更新

Environment variables in PHP source

Far too often you come across a project on GitHub and you notice that the original developer has left in a config.php file that contains (in the best case) useless database information or (in the worst case) incredibly important API keys.

When these files aren't accidentally versioned they are often shoved in a .gitignore file with a sample file attached for developers to amend as they need. One example of a platform that does this is WordPress.

There are some minor improvements to this, such as putting core configuration in an XML file that is buried in some obscure document with plenty of irrelevant configuration.

I've found that there tend to be two good ways of managing environment variables in PHP. The first method involves putting them in a file on your root folder in a format such as YML and reading these variables as required.

The second way, which I personally prefer, is a method implemented by a library known as dotenv. Essentially, what happens is there is a .env file is created and put in the room of your project. In order to read configuration from this file, you just need to call the env() function. You can then add this file to your .gitignore file so that when you push from your development environment and pull to various other server configurations this process is made easier. In addition to this, you can specify environment variables at the web server level, thus ensuring an additional level of security and also making management far easier.

So, for example, if my .env file had a DB_HOST property, then I can access it using env('DB_HOST');.

If you do go down the dotenv route, be sure to make sure that your .env is not publically visible from the document root. Either keep it out of your public HTTP directory (for example, in the level above), or restrict access to it at a web server level (for example, restrict permissions, or if you're using Apache, use your .htaccess file to limit access to it).

At the time of writing, you can require this library by simply running the following command:

composer require vlucas/phpdotenv

Soft Code may often also be an anti-pattern that is adopted by using configuration files. This is where you start putting business logic in configuration files instead of source code; therefore, it is worth reminding yourself to consider when something really needs to be configuration oriented.