Reputation: 207
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?
Upvotes: 2
Views: 307
Reputation: 2039
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
Upvotes: 2
Reputation: 499
However, for keeping your credentials safe I suggest to use dotenv I think it's probably the best way to do that.
Good luck.
Upvotes: 1
Reputation: 7785
Configurations and parameters must be set outside of your PHP project
You have to keep in mind that this kind of work can be managed by a person that is not a developer, knowing nothing about PHP programming
Use something standard for this : like XML, properties or conf files
Upvotes: 1