22.11 2010

Иранский программист Muhammad Hussein Fattahizadeh предложил довольно интересный способ древовидного хранения настроек приложения. Я приведу вольный перевод описания опубликованного в его блоге

Лучшая часть моего любимого php фреймворка zend framework - это Zend_Config. С помощью Zend_Config вы можете дать своему вебприложение более тонкую настройкой, что бы каждый смог настроить его по своему вкусу.

Вы можете больше прочитать про Zend_Config на странице официального мануала.

Большинство вебприложений имеют много конфигурационных файлов, с разными форматами, такими как INI, XML или PHP. Также некоторые из этих файлов могут отвечать лишь за часть вашего приложения, и находится в специальной директории.

Моя структура директорий

Итак, это моя дефолтная структура приложения основанного на Zend Framework. В ней вы можете увидеть множество конфигурационных файлов.

My Zend framework folder structure

Стандартное решение, предполагает загрузку каждого файла отдельно, а также раздельный доступ к объектам. Что не всегда удобно.

Мое решение проблемы с помощью класса Zend_Config

/**
 * @copyright Copyright(c) Muhammad Hussein Fattahizadeh. All rights reserved.
 * @author Muhammad Hussein Fattahizadeh
 * @link <http: //mhf.ir/>;
 */

class My_Config
{
    /**
     * Base folder that contain config files
     * @var string
     */
    private $_baseFolder;

    /**
     * Create config object
     */
    public function __construct($baseFolder)
    {
        // check for valid folder
        if(is_dir($baseFolder)) $this->_baseFolder = $baseFolder;
        else throw new Zend_Exception("Invalid base folder for configurations.");
    }

    /**
     * Set the config object is return the error.
     * @param string $name
     * @param object $value
     */
    public function __set($name, $value)
    {
        throw new Zend_Exception("Configurations is readonly.");
    }

    /**
     * Get the config data
     * @param string $name
     * @return object
     */
    public function __get($name)
    {
        // set the configuration file path and format
        list($fileFormat, $configPath) = $this->_solvePath($name);

        // switch format for get configuration type
        switch ($fileFormat) {
            case 'ini':
                $value = new Zend_Config_Ini($configPath);
            break;
            case 'xml':
                $value = new Zend_Config_Xml($configPath);
            break;
            case 'php':
                $value = new Zend_Config(require $configPath);
            break;
        }
        return $value;
    }

    /**
     * Path solver
     * @param string $pathString
     * @return array
     */
    private function _solvePath($pathString)
    {
        // set file format
        $explodePath = explode('_', $pathString);
        $fileFormat = end($explodePath);
        if(!in_array(strtolower($fileFormat), array('ini', 'xml', 'php'))) throw new Zend_Exception("Invalid configuration file format.");

        // process path
        array_pop($explodePath);
        $configPath = implode(DIRECTORY_SEPARATOR, $explodePath);

        // return data
        return array(strtolower($fileFormat), $this->_baseFolder . DIRECTORY_SEPARATOR . $configPath . '.' . $fileFormat);
    }
}

и пример использования

$config = My_Config('/path/to/project/application/configs');

// just dont forget last part of get method for config is file format look at the examples

// load '/path/to/project/application/configs/database/mysql/news.xml' and get node adapter data
echo $config->database_mysql_news_xml->adapter;

// load '/path/to/project/application/configs/database/mysql/articles.ini' and get node 'params->username' data
echo $config->database_postgresql_articles_ini->params->username;
comments powered by Disqus