开发者

Dependency injection class - where to store configs

When using dependency injection for database handlers etc instead of singleton - where is it best to keep the configs I.e. Username pas开发者_StackOverflow中文版sword host etc. Keep inside the class, use a container class or use a static configs class or use a file?


I generally keep them in a file outside of the webroot.


External config file that returns an array is a quick solution:

config.php:

<?php
 return array(
   'database'=> array(
     'host'=> 'localhost',
     'dbname'=> 'name_of_db',
     'username'=> 'myusername',
     'password'=> 'mypassword',
   ),
 );

test.php:

<?php
$config = include('config.php');
mysql_connect($config['database']['host'], $config['database']['username'], $config['database']['password']);
....

Ideally, store the config file in a directory that can be read by the anonymous web user (but not written).


This is difficult to get 'right' because it depends on the exact use-case. But here's what I did when I had a very similar problem.

I had setup a shared library system for a small number of websites. Initially, it provided just a database handler, but there was quickly added an ORM layer. Most of the growth after that was additional objects as one of the websites was rewritten away from direct SQL into object-based access. There was also a configuration library used to define how the objects and other elements in the shared library were collected together into 'modules' as well as default settings for things like database settings. It also supported loading a configuration file outside the code-tree, which was used to per-host settings.

Since the objects in the ORM layer had to configure themselves (there was a static call to do that as they were declared), it was trivial for it to be extended to request a particular database by name, too. Then it was a matter of making sure that all these database definitions were declared as well (and were overridable thanks to the generic configuration mechanism).

(It took a while, but when we did reach the point of having to split the database, it was very easy to point the relevant objects off to another database and everything just kept working.)

To answer your question, though: the configuration was split. Database hostnames, usernames and passwords were all named and defined in one place in the in-code configuration area. But they could be overridden on a per-host basis. Per object settings were where the objects were declared. And that was also where the database configurations were specified by name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜