Is it good or bad to store the DB connection details with define()?
define( 'DB_HOST', 'localhost' );
define( 'DB_USER', 'root' );
define( 'DB_PASS', 'xxx' );
define( 'DB_NAME', 'xxx' );
or better in an array below?
$config['db'] = array(
'driver' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'user' => 'someuser',
'password' => 'SuperSecretPassword',
'name' => 'db_name',
);
I notice that popular frameworks such as Zend or Symfony don't use define for this configuration.
CodeIgniter,
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
...
What are the benefits of storing it in an array instead of define()
? I notice that Zend appears does not use define()
at all (I might be wrong as I am new to Zend). Is it bad to store somme global contants then in general?
In my limited knowledge, I do find storing some global contants useful, for instance, I can store my document root in this below then I can access it from everywhere - by just using WEBSITE_DOCROOT
define ( 'WEBSITE_DOCROOT', str_replace( '\\', '/', dirname( __FILE__ ) ).'/' );
Unlike this method below that I have to use dirname(__FILE__)
everytime,
// Load config file
$configFile = dirname(__FILE__) . '/../share/config/default.php';
which I could just use WEBSITE_DOCROOT . '/../share/config/default.php';
to call the file. Isn't it easier and consistent?
There is no limitation to use define
instead of array
. Frameworks use arrays
for database connections functions because they want to have some optional
parameters like encoding
. another reason is there is no needs to define
these consts and save memory for them while you just need them once(at bootstrap.php). the idea of define
is accessing const everywhere, but for database configurations you don't need it.
*it is better to store database configurations in a file with read-only
and not executable
permission for apache
and deny all access for other users. so this file could not be a php file. you can use xml
, ini
or other standard formats
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments