When we are not using a framework ,
what is the best way to store configs in a composer project and how we can load them from a controller or a model file? prefer we can store configs outside the src
folder.
why nobody using class constants to store configs
ex. App/Config/AppConfig::TIMEZONE;
- composer.json
"autoload":
{
"psr-4":
{
"App\\": "src/app/"
}
}
- /src/app/Configs/AppConfig.php
namespace App\Configs;
class AppConfig {
const TIMEZONE = 'EST';
}
- src/app/Controllers/HelloWorld.php
namespace App\Controllers;
use App\Configs\AppConfig;
class HelloWorld
{
$timezone = AppConfig::TIMEZONE;
}
Thanks
In a modern world, things are going modern. Best approach for configurations are separately save in directory. Now it's time to talk on calling configuration values; Create helper function which will gather data for you and efficiently return as you wanted.
I use this PHPConfig Package to do that kind of thing.
This approach lets you store all of your config items in a separate place to the rest of your code, and gives you easy access to any config values anywhere in your application.
Directory Structure
- app
- app.php
- config
- config_file_one.php
- config_file_two.php
- public
- index.php
config_file_one.php
<?php
use TomWright\PHPConfig\Config;
$config = Config::getInstance();
$config->setItem('mysite.name', 'My Site');
config_file_two.php
<?php
use TomWright\PHPConfig\Config;
$config = Config::getInstance();
$config->setItem('mysite.url', 'https://www.example.com');
app.php
<?php
use TomWright\PHPConfig\Config;
class App {
public function __construct()
{
$this->loadConfigFiles();
}
private function loadConfigFiles()
{
require_once '/path/to/app/config/config_file_one.php';
require_once '/path/to/app/config/config_file_two.php';
}
public function run()
{
$config = Config::getInstance();
var_dump($config->getItem('mysite.name')); // My Site
var_dump($config->getItem('mysite.url')); // https://www.example.com
var_dump($config->getItem('mysite')); // stdClass { name => 'My Site', url => 'https://www.example.com' }
}
}
index.php
<?php
require_once './vendor/autoload.php';
$app = new App();
$app->run();
You can go one step further and automatically include all php files under the config directory.
You can also define different config items depending on environment variables and system settings, such as development and production environments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.