SugarCRM的配置文件在项目目录/config.php和config_override.php中,其中config_override.php可以替换config.php中的配置。解析配置文件就是在SugarConfig和SugarArray两个类进行的。
在./include/entryPoint.php引入require_once 'include/SugarObjects/SugarConfig.php',然后在./include/utils/autoloader.php中实例化$config = SugarConfig::getInstance(),如获取$config->get('developerMode'),接下来看看代码流程。【此步骤是以入口流程中进行的,即index.php--->entryPoint.php--->autoloader.php】
class SugarConfig { var $_cached_values = array(); // 单例 static function getInstance() { static $instance = null; if (is_null($instance)) { $instance = new SugarConfig(); } return $instance; } // 在首次获取的时候,引入array_utils.php,第二次就直接从缓存中获取 function get($key, $default = null) { if (!isset($this->_cached_values[$key])) { if (!class_exists('SugarArray', true)) { require 'include/utils/array_utils.php'; } $this->_cached_values[$key] = isset($GLOBALS['sugar_config']) ? SugarArray::staticGet($GLOBALS['sugar_config'], $key, $default) : $default; } return $this->_cached_values[$key]; } // 清除 function clearCache($key = null) { if (is_null($key)) { $this->_cached_values = array(); } else { unset($this->_cached_values[$key]); } } } // 这里继承了php自带的ArrayObject类,把数组转成了对象 class SugarArray extends ArrayObject { /** * Return the value matching $key if exists, otherwise $default value * * This method uses dot notation to look through multi-dimensional arrays * * @param string $key key to look up * @param mixed $default value to return if $key does not exist * @return mixed */ public function get($key, $default = null) { return $this->_getFromSource($key, $default); } /** * SugarConfig首先调用此方法,进入此方法后,调用get方法,再调用_getFromSource方法 * 如果配置文件的相关键为多维数组,那么递归调用_getRecursive获取 * 若是掉用的键不在配置文件内,则返回$default * Provided as a convinience method for fetching a value within an existing * array without instantiating a SugarArray * * NOTE: This should only used where refactoring an array into a SugarArray * is unfeasible. This operation is more expensive than a direct * SugarArray as each time it creates and throws away a new instance * * @param array $haystack haystack * @param string $needle needle * @param mixed $default default value to return * @return mixed */ static public function staticGet($haystack, $needle, $default = null) { if (empty($haystack)) { return $default; } $array = new self($haystack); return $array->get($needle, $default); } private function _getFromSource($key, $default) { if (strpos($key, '.') === false) { return isset($this[$key]) ? $this[$key] : $default; } $exploded = explode('.', $key); $current_key = array_shift($exploded); return $this->_getRecursive($this->_getFromSource($current_key, $default), $exploded, $default); } private function _getRecursive($raw_config, $children, $default) { if ($raw_config === $default) { return $default; } elseif (count($children) == 0) { return $raw_config; } else { $next_key = array_shift($children); return isset($raw_config[$next_key]) ? $this->_getRecursive($raw_config[$next_key], $children, $default) : $default; } } }