Search code examples
phpglobal-variablesscopeglobal-scope

Recommended way to manage global scope data and settings in PHP?


After a few years in PHP development, I saw and heard various ways for storing "global scope data" (globals, constants, ini/XML/YML files, database, singleton properties...).

By "global scope data", I mean:

  • Global application/project settings such as
    • Database configuration
    • SMTP, FTP parameters
  • Database identifiers (e.g. primary key values for specific languages or countries defined in DB)
  • Global runtime settings such as
    • Enable logging / debug
    • Environment is dev / test / prod
  • etc.

... which are not supposed to change once retrieved, and need to be easily reachable in any part of the project code.

Some global data may need to be stored as associative array (so cannot be declared as constant).
For example: date formats per language. BTW, I saw this other SO question about array constants, but isn't there something more readable than using unserialize everywhere an array constant value is needed?

My main question is: what is the way you would recommend to store properly (I mean clean, readable, reliable) global scope data, and why (pros/cons)?

Thanks.


Solution

  • You can look at Zend_Config for the most frequent implementations of config.

    • array (php only, immediate but scattered and harder to read)
    • ini (easy to read and write by hand)
    • xml (verbose and harder to handle but very flexible)
    • json (pretty easy to read, can be great if you want to access it directly via js too)
    • yaml (you write directly a serialized array basically)

    Of course array may seem the most immediate and uncomplicated solution since it's pure PHP and doesn't need any special parser or writer.

    On the other hand the other formats have clear advantages too. The Zend_Config documentation writes for example about ini files.

    The INI format is specialized to provide both the ability to have a hierarchy of configuration data keys and inheritance between configuration data sections. Configuration data hierarchies are supported by separating the keys with the dot or period character (".").

    Using constants is not a good idea because:

    1. your application doesn't need to see all your config options all of the time and
    2. more importantly you cannot nest constants and nesting is something really important for configuration.