Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Zend_Config_Ini and a string

DZone's Guide to

Zend_Config_Ini and a string

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, brought to you in partnership with Qlik.

One thing that is different between Zend_Config_Xml and Zend_Config_Ini is that with Zend_Config_Xml you can pass in an XML string as the first parameter of the constructor and it will work. This doesn't work with Zend_Config_Ini as we use parse_ini_file() under the hood.

With PHP 5.3 however there is is a new function called parse_ini_string() which will allow us to load arbitrary ini string into Zend_Config objects. This can't go into Zend Framework 1 though due to our PHP 5.2.4 minimum version requirement.

As I needed this for a project, I extended Zend_Config_Ini to support this feature, which means simply overloading a single method

class App_Config_Ini extends Zend_Config_Ini
{
    /**
     * Load the INI file from disk using parse_ini_file(). Use a private error
     * handler to convert any loading errors into a Zend_Config_Exception
     *
     * @param string $filename
     * @throws Zend_Config_Exception
     * @return array
     */
    protected function _parseIniFile($filename)
    {
        set_error_handler(array($this, '_loadFileErrorHandler'));
        if (substr($filename, -4) == '.ini') {
            $iniArray = parse_ini_file($filename, true);
        } else {        
            $iniArray = parse_ini_string($filename, true);
        }
        restore_error_handler();

        // Check if there was a error while loading file
        if ($this->_loadFileErrorStr !== null) {
            /**
             * @see Zend_Config_Exception
             */
            require_once 'Zend/Config/Exception.php';
            throw new Zend_Config_Exception($this->_loadFileErrorStr);
        }

        return $iniArray;
    }
}

The actual change is to see if the last 4 characters of the filename are ".ini" and if they aren't then use parse_ini_string() instead of parse_ini_file(). The rest of the code is just error handling.

This is one area where I really like it when a class implements methods that done just one thing.


Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}