This is a showcase how you can implement Laravel like .env file structure in your CodeIgniter application, and make configurations easy for all the development, production, testing stages. You don't need to take care of application/config/database.php
file each time you do git pull
or put it in .gitignore
.
Run
composer require vlucas/phpdotenv
command in your project root directory. (If you don't have composer.json, don't worry, composer will take care of it.
This will load your env file in environment.
If you are using vulcas/phpdotenv >= 4.x.x
, then change code accordingly as mentioned in Env.php
file.
This will add
env
helper method to get any variable stored in.env
file.
Add library to
$autoload['libraries']
like this
$autoload['libraries'] = array('env');
Add helper to
$autoload['helper']
like this
$autoload['helper'] = array('general');
Make
composer_autoload
tovendor/autoload.php
file path like this inconfig.php
file
$config['composer_autoload'] = FCPATH. 'vendor'. DIRECTORY_SEPARATOR . 'autoload.php';
Create an .env
file in your project root folder.
In your php code you can access any .env variable like below
env('MY_VARIABLE');
Voila ! Now you can have multiple variables based on Environment, and don't need to manually change file and then put it in .gitignore
.