Correct way of defining configuration settings - php

I use a global array to define certain configurations for my application. But so far I've read that globals are bad practice and should be avoided. This global is read-only, so I'm not altering it in any way in my code.
What would be the correct way of defining configuration settings?
$GLOBALS['config'] = array(
'mysql' => array(
'host' => 'localhost',
'username' => 'user',
'password' => 'password',
'database' => 'database'
),
'navigation' => array(
'Home' => array('/', '/index.php'),
'Sign up' => array('/signup', '/signup.php'),
'Log in' => array('/login', '/login.php')
)
);

Start with a Configuration class to hold all settings in a collection of key->value pairs and getter and setter methods. This class is part of the normal application code.
To be able to handle different settings for each environment, like the connection parameters in your example, use multiple files.
For each environment a folder exists to store the all environment-specific configuration files.
One of the files stored here is a script that:
creates a static configuration object
sets all configuration parameters to the values for that environment.
Other parts of the application use this static object to get the settings from.
The files in the different folders have equal names, for example in this structure:
- config
- development
- config.php
- staging
- config.php
- production
- config.php
During deployment the configuration files for the environment that you are deploying to are included. What I do is also put the deployment scripts in these folders.
This setup supports multiple environments and you can keep the files with configuration settings under version control.

I don't have much of an idea of PHP. But with respect to OOP, you can create a class(possibly named Config) which contains static read-only variables. And then use them as follows
Config.mysql and Config.navigation

Related

Proper way to call .env file inside project

I wanted to see what would be the proper way to call a .env file inside my project? One of the developers that I'm working with, just told me that everything is setup and that all I would need is to create a .env file in the root.
Here is how the function is being called:
$settings = [
'name' => 'DB_NAME',
'user' => 'DB_USER',
'password' => 'DB_PASSWORD',
'host' => 'DB_HOST',
];
I have my .env file setup as the following (I've created the local database using the below credentials):
cc
cc_user
Z_______0!
localhost
Is this the correct method? Do I need quotes around the name, user, password and host inside the .env file? I am doing all this on a localhost environment.
Your .env file should look like this:
DB_NAME=cc
DB_USER=cc_user
DB_PASSWORD=Z_______0!
DB_HOST=localhost
You don't need quotes here
I suspect you need to set up your .env file with KEY=value pairs, something like
DB_NAME='mydatabase'
Your code sample doesn't give enough to know for sure, but the first thing that comes to mind for me is npm's dotenv package, documentation for which can be found here - https://www.npmjs.com/package/dotenv

How to access at the local configuration on Zend Framework 2

I have some configuration on local/config/xxx/config.ini and a local/config/xxx/config_base.ini.
How can I access at there configuration on Zend Framework 2. I have an instance of the ServiceProvider but I cannot access at these config. It only ready the module.config.php (ex with $config = $sm->get('Config');)
I found that I can use this for read an ini file:
$config = (new Zend\Config\ReaderIni())->fromFile(getcwd() . '/local/config/xxx/config.ini');
But then how to merge the two configurations?
Why would do you use .ini extension for your config files? As you can read in the documentation on Advanced Configuration Tricks config files should be stored as .php files. They contain arrays holding the keys and values of your configuration and they will be automatically read from the autoload folders and merged with the module configuration files.
Once configuration is aggregated from all modules, the ConfigListener will also merge application configuration globbed in specified directories (typically config/autoload/).
Here you can also find the folder pattern used to find the files it needs to merge:
// An array of paths from which to glob configuration files after
// modules are loaded. These effectively overide configuration
// provided by modules themselves. Paths may use GLOB_BRACE notation.
'config_glob_paths' => array(
'config/autoload/{{,*.}global,{,*.}local}.php',
),
The advantage is that you don't need a separate file reader and you can access your custom config from the service manager directly like you would do for other configs.
$config = $sm->get('Config');
$webhost = $config['my_param'];
Another advantage is that you can setup your production environment to cache the config files which will dramatically increase the performance of the bootstrapping procedure (reading files is a slow process).
I would suggest you rename your file extension to .php and follow the documentation for setting up your custom configuration values.
When using the skeleton application, the system configuration is by default in config/application.config.php.
/ config.php
return array(
'webhost' => 'www.ekio.rw',
'database' => array(
'adapter' => 'pdo_mysql',
'params' => array(
'host' => 'db.ekio.rw',
'username' => 'dbuser',
'password' => 'secret',
'dbname' => 'mydatabase'
)
)
);
Then,
// Consumes the configuration array
$config = new Zend\Config\Config(include 'config.php');
// Display a configuration datum (results in 'www.ekio.rw')
echo $config->webhost;

Best practice - Distinguish between environments (PHP)

I need to make some slight configuration changes in my local dev env.
Thus, I would like to know what is the "best practice" in distinguishing between environments.
I would like to have only one config file which will behave differently depending on which environment it is executed.
Common and good practice is to use different .env files on different environments.
Basically, a .env file is an easy way to load custom configuration
variables that your application needs without having to modify
.htaccess files or Apache/Nginx virtual hosts. This means you won't
have to edit any files outside the project, and all the environment
variables are always set no matter how you run your project - Apache,
Nginx, CLI, and even PHP 5.4's built-in webserver. It's WAY easier
than all the other ways you know of to set environment variables, and
you're going to love it.
You can use some already created packages to add this to your project. Check this one: https://github.com/vlucas/phpdotenv
Example (just for a demo, not production ready code!):
Note! You will need to add .env to .gitignore file to keep it not synced between environments.
Development .env file:
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=
Production .env file:
DB_HOST=192.168.10.1
DB_USER=dbUser
DB_PASSWORD=123456
Possible config.php file:
<?php
// add composer autoload somewhere here...
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
return [
'db' => [
'host' => getenv('DB_HOST'),
'user' => getenv('DB_USER'),
'pass' => getenv('DB_PASSWORD'),
]
]

How to make ZF2 db credentials environment specific

I am starting a new project.
I am using ZF2. I have just installed it and have the Skeleton application up and running.
This is my deployment process:
I develop on my local machine
I then push to my public github repository
I then use deployhq.com to deploy those to my production
server which is where the user would see the changes made.
I have tried to look around stack, zend site, and google at blogs etc but still dont have any real understanding or solution to my problem.
I want the application to use different database credentials based on its environment. E.g. if on 'dev', my local machine, then use credentials A, but if on live server, then use credentials B.
I have read a lot about global and local autoload config files etc, but baring in mind my github repo is public, any where I commit any config files with my db details would be visible.
I was wondering if there was a way to have, the same theory, global and local files with the DB connections in, i upload the production details manually, not via git for security reason, and tell git to ignore the local config file somehow? I would also need to know how I tell the application to use those config files based on the environment and there location.
In Zend 2 There are
Global configuration file &
Module level configuration file
IF you want to know there use you can refer the link below
How does configuration works in ZF2
When I had a same scenario I used the above link to understand and exploit Zend Config module which is really good to handle the situation like this .
create two files
production.php
local.php
in both these files
return this array based on the environment
return array(
"dbname" => "yourdbname"
"dbhostname" => "dbhostname"
"dbusername" => "yourdbusername",
"dbpassword" => "yourdbpassword"
);
in config/autoload/ directory of your zend framewrok application
later edit your config/application.config.php file as per below instructions
// get the application env from Apache vhost file ( here you can set in your apache vhost file as production or local )
$applicationEnv = getenv('APPLICATION_ENV');
$environmentSpecificConfigPath = "config/autoload/{,*.}{".$applicationEnv.",local}.php";
// Next with in the config array pass the environment specific configuration path
'config_glob_paths' => array($environmentSpecificConfigPath)
in any controller or action
you can just use the below code
$configArray = $this->getGlobalConfig();
Now $configarray has all your DB credentials to create a connection
$adapter = new Zend\Db\Adapter\Adapter(array(
'driver' => 'Mysqli',
'database' => $configArray['dbname'],
'username' => $configArray['dbusername'],
'password' => $configArray['dbpassword']
));
If you use config array to connect the DB in your entire application
you dont need to worry about environment changes just make sure you have an Apache APPLICATION_ENV entry in your vhost file
you can do that by adding below line in your apache vhost file
SetEnv APPLICATION_ENV "production" // in your production server
SetEnv APPLICATION_ENV "local" // in your local
Also Last but not least you can use the Zend Experts module ZeDB
https://github.com/ZendExperts/ZeDb
To manage your CRUD applications
Hope the above steps may help you in creating the environment

ZF2: how to implement different configs for production, staging etc?

In the sceleton application that I've downloaded from github there is a file
module/Application/config/module.config.php
return array(
'layout' => 'layout/layout.phtml',
'display_exceptions' => true,
'di' => array(
'instance' => array(
'alias' => array(....
this file is used in module/Application/module.php:
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
How to create 3 different configs depending on domain (production, staging, development)? It seems in ZF1 env vars has been used, but I don't know how to do that in zf2 module.
Thank you!
Create a file called development.config.php in application/config/autoload and this will be loaded after all the modules' config files have been loaded. As a result, you can override anything the merged configuration by adding the relevant keys to this file.
The name of the file loaded is {APPLICATION_ENV}.config.php, so you can create production.config.php, etc.
Note that you may have to change the glob in index.php as it's unclear if the Skeleton application will work out of the box with APPLICATION_ENV or not at this stage of the development of ZF2 (early April 2012).
it seems to work with a simple .htaccess change. :
SetEnv APPLICATION_ENV development
I don't know if staging will work, but production and development work out of the box.
I think it works through the event listener, but don't ask me how, I haven't gotten that far yet.

Categories