Zend Config XML and INI files - How to Specify False and Other Non-String PHP Data Types

Zend Config INI and Zend Config XML are handy adaptors that allow you to store configuration data in easy-to-edit text file formats.

The data can take the form of a hierarchy and they also make it easy to avoid repetition by using inheritance - where one section of the configuration data can inherit from another. So, a fish and a dog can both inherit properties of, say,  an animal.

I would normally use arrays to store my config data because it is such a familiar construct. But, managing inheritance with arrays can get very complex. So,  if I need to manage inheritable data I fall back onto to using INI’s. Inheritance is clear with INI’s.  Then, if the data values spread over multiple lines and become large and complex, I resort to XML. We all have our preferences I suppose.

Unfortunately these config files store strings and cannot store special PHP data types like NULL, FALSE,  or TRUE. We have to make Zend Config convert strings into special types if we need them.

See syntax and caveats for ini files: http://uk3.php.net/parse_ini_file

As the Zend Framework Documentation says:

Note: Return Type
Configuration data read into Zend_Config_Xml are always returned as strings. Conversion of data from strings to other types is left to developers to suit their particular needs.

One way to overcome this issue is to have special case strings which can be used as values in the config file - like “NULL” and “BOOLEAN_FALSE”.

Then, once a config object has been loaded with config data, you can use a helper routine to recursively iterate through its values and fix them.

If a value matches one of those special values, the helper routine modifies the property value replacing the special case string into the appropriate PHP  data type.

In order to do this one has to ensure that the config object is not read-only (ie. passing TRUE as the third argument to the adapter’s constructor). Once the fix has been done, you could then mark it as read-only via the setReadOnly() method.

See example code:

It might be sensible to make this helper routine a method of the Zend_Config object itself by extending the Zend_Config_Xml class.

Also it would probably be sensible to make those strings into CONSTANTS in order to indicate their special meaning.

The code example above has the following output:

Before Fix

dog

Array
(
    [number_of_legs] => 4
    [number_of_fins] => NULL
    [type] => dog
)

They tend to have 4 legs
They tend to have NULL fins

fish

Array
(
    [number_of_legs] => NULL
    [number_of_fins] => 6
    [type] => fish
)

They tend to have NULL legs
They tend to have 6 fins

After Fix

dog

Array
(
    [number_of_legs] => 4
    [number_of_fins] =>
    [type] => dog
)

They tend to have 4 legs

fish

Array
(
    [number_of_legs] =>
    [number_of_fins] => 6
    [type] => fish
)

They tend to have 6 fins

Leave a Reply