$settings array or Config Class to store project s

2020-05-24 04:20发布

How should I store settings for project?

Which is better - to use a $settings array with all my settings:

$settings['max_photos'] = 30;
//...

or create a singleton Config class with all the settings in it?

Class Config {
    private $max_photos = 30;
    //...
}

Any good examples?

7条回答
倾城 Initia
2楼-- · 2020-05-24 05:18

I tend to put configuration values that are only accessed globally in a config array and define values that are accessed anywhere. For example:

inc/config.php

// only accessed in global scope (see init.php)
$config['error_reporting'] = E_ALL & ~E_NOTICE;
$config['memory_limit'] = '16M';
$config['time_zone'] = 'America/Los_Angeles';

// accessed within functions or class methods (see somefile.php)
define('HTTP', 'http://imac.local/my_site/');
define('HTTPS', 'http://imac.local/my_site/');
define('FILE_ROOT', '/Library/WebServer/Documents/my_site/');

inc/init.php

require 'inc/config.php';

/* Set some php configurations */
isset($config['error_reporting']) ? error_reporting($config['error_reporting']) : '';
isset($config['time_limit']) ? set_time_limit($config['time_limit']) : '';
isset($config['memory_limit']) ? ini_set('memory_limit', $config['memory_limit']) : '';
isset($config['timezone']) ? date_default_timezone_set($config['timezone']) :  date_default_timezone_set('America/Los_Angeles');

somefile.php

require 'inc/init.php';

function site_url($uri, $secure = FALSE)
{
    return $secure ? HTTPS . $uri : HTTP . $uri;
}

Keep in mind this example is stripped down to demonstrate an idea.

查看更多
登录 后发表回答