1: <?php
2: /**
3: * This file contains classes implementing configuration feature.
4: *
5: * @author Qiang Xue <qiang.xue@gmail.com>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11:
12: /**
13: * CConfiguration represents an array-based configuration.
14: *
15: * It can be used to initialize an object's properties.
16: *
17: * The configuration data may be obtained from a PHP script. For example,
18: * <pre>
19: * return array(
20: * 'name'=>'My Application',
21: * 'defaultController'=>'index',
22: * );
23: * </pre>
24: * Use the following code to load the above configuration data:
25: * <pre>
26: * $config=new CConfiguration('path/to/config.php');
27: * </pre>
28: *
29: * To apply the configuration to an object, call {@link applyTo()}.
30: * Each (key,value) pair in the configuration data is applied
31: * to the object like: $object->$key=$value.
32: *
33: * Since CConfiguration extends from {@link CMap}, it can be
34: * used like an associative array. See {@link CMap} for more details.
35: *
36: * @author Qiang Xue <qiang.xue@gmail.com>
37: * @package system.collections
38: * @since 1.0
39: */
40: class CConfiguration extends CMap
41: {
42: /**
43: * Constructor.
44: * @param mixed $data if string, it represents a config file (a PHP script returning the configuration as an array);
45: * If array, it is config data.
46: */
47: public function __construct($data=null)
48: {
49: if(is_string($data))
50: parent::__construct(require($data));
51: else
52: parent::__construct($data);
53: }
54:
55: /**
56: * Loads configuration data from a file and merges it with the existing configuration.
57: *
58: * A config file must be a PHP script returning a configuration array (like the following)
59: * <pre>
60: * return array
61: * (
62: * 'name'=>'My Application',
63: * 'defaultController'=>'index',
64: * );
65: * </pre>
66: *
67: * @param string $configFile configuration file path (if using relative path, be aware of what is the current path)
68: * @see mergeWith
69: */
70: public function loadFromFile($configFile)
71: {
72: $data=require($configFile);
73: if($this->getCount()>0)
74: $this->mergeWith($data);
75: else
76: $this->copyFrom($data);
77: }
78:
79: /**
80: * Saves the configuration into a string.
81: * The string is a valid PHP expression representing the configuration data as an array.
82: * @return string the string representation of the configuration
83: */
84: public function saveAsString()
85: {
86: return str_replace("\r",'',var_export($this->toArray(),true));
87: }
88:
89: /**
90: * Applies the configuration to an object.
91: * Each (key,value) pair in the configuration data is applied
92: * to the object like: $object->$key=$value.
93: * @param object $object object to be applied with this configuration
94: */
95: public function applyTo($object)
96: {
97: foreach($this->toArray() as $key=>$value)
98: $object->$key=$value;
99: }
100: }
101: