Reputation: 1594
I have a Phalcon project with this library added: https://github.com/vlucas/phpdotenv. This library is meant to load some environment variables from a .env file. I created such a file and put it in my project.
VERSION_NUMBER=3.14
DATABASE_HOST=localhost
DATABASE_NAME=test
DATABASE_USER=root
DATABASE_PASS=root
I rewrote my loader.php
file to the code below:
<?php
$loader = new \Phalcon\Loader();
/**
* We're a registering a set of directories taken from the configuration file
*/
$loader->registerNamespaces(array(
'Test\Models' => $config->application->modelsDir,
'Test\Controllers' => $config->application->controllersDir,
'Test\Forms' => $config->application->formsDir,
'Test\Classes' => $config->application->classesDir,
'Test\Classes\Excel' => $config->application->excelDir,
'Test' => $config->application->libraryDir
));
$loader->register();
// Use composer autoloader to load vendor classes
require_once __DIR__ . '/../../vendor/autoload.php';
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->required(['DATABASE_HOST', 'DATABASE_NAME', 'DATABASE_USER', 'DATABASE_PASS']);
$dotenv->overload();
And in my config file I replaced the keys with the environment variables:
'database' => array(
'adapter' => 'Mysql',
'host' => getenv('DATABASE_HOST'),
'username' => getenv('DATABASE_USER'),
'password' => getenv('DATABASE_PASS'),
'dbname' => getenv('DATABASE_NAME')
),
I can echo getenv('VERSION_NUMBER')
where I want and it works every time, but when I try to use this config file the variables are empty. What am I doing wrong?
Upvotes: 3
Views: 2740
Reputation: 5213
Judging from the source code excerpts you've provided, there is no reason why it shouldn't work. I can only make assumptions, but since I'm currently developing a project which uses Dotenv as well, I'd like to point out two possibilities.
Firstly, I'm not sure why you're using the overload()
Method. It's completely sufficient to load Dotenv like this in your public/index.php
:
define('APP_PATH', realpath('..'));
include APP_PATH . '/vendor/autoload.php';
$dotenv = new Dotenv\Dotenv(APP_PATH);
$dotenv->load();
This brings me to the second and most likely source of your problem:
You're loading Dotenv in the loader.php
file. In most Phalcon example projects, that one is loaded after the config, therefore your Env variables aren't set at that point yet. Include the code I mentioned in your index.php
and you should be good.
Upvotes: 5