Is it right to set a config PHP class to keep project settings?

Amr picture Amr · Jun 11, 2012 · Viewed 28.3k times · Source

I want to create a config.php file to keep the various configuration values that usually being changed from project to project, and I want to define a class to keep the config values in this file like the following:

class Config {
    const DB_SERVER    = 'localhost',
          DB_NAME      = 'abc',
          DB_USERNAME  = 'admin',
          DB_PASSWORD  = '12345',

          WEBSITE_NAME = 'My New Website',
          IMAGE_DIR    = 'img';
}

and so on, I want to define all values as constants inside the class, and I will call them like the following:

$connection = mysql_connect(Config::DB_SERVER, Config::DB_USERNAME, Config::DB_PASSWORD) or die("Database connection failed..");

I want to know: Is this way of setting the project configuration is right? Does this way have any cons? And if it was wrong, then what the best way to do this?

Answer

cHao picture cHao · Aug 17, 2012

It's one way of doing it, yes. A not-too-bad way, IMO. Basically the class becomes a config file, just with PHP syntax.

There are a couple of drawbacks, though:

  • You can't have const arrays or objects. (Course, you can't have global constant arrays/objects either, so...) (Since 5.6, you can have constant arrays. Still no const objects, though. I'm pretty sure you can't have const resources either, as that wouldn't make much sense.)

    You can work around this by implementing a static getter for objects (which of course is coded to always return the same object)...but i'd recommend against it in most cases. It is only a safe option if the objects in your config are immutable by design. (Objects that aren't designed for immutability are way too easy to change, even by accident.)

    (Aside from the mutability issue, it bugs me having actual running code in a config file...but that's mostly personal preference.)

  • This class has a different purpose than the rest -- it's intended to change per project. You might consider keeping the Config class somewhere apart from the rest of the classes, like where you'd normally keep a config file.

  • With a real config file, since you parse it at runtime, you could conceivably deal with a missing or invalid file (say, by running with default settings, using what parts are parsable, and/or showing a useful error message). But once your configuration is running as PHP code, any syntax errors -- or, if you haven't accounted for it, a missing Config class -- will stop the app dead in its tracks. And if you're running with display_errors off (recommended in production), the problem might be less than obvious.