Object.php 10.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?php
/**
 * Object class file.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright &copy; 2008-2012 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

/**
 * Object is the base class that implements the *property* feature.
 *
 * A property is defined by a getter method (e.g. `getLabel`),
 * and/or a setter method (e.g. `setLabel`). For example, the following
 * getter and setter methods define a property named `label`:
 *
 * ~~~
 * private $_label;
 *
 * public function getLabel()
 * {
Qiang Xue committed
24
 *	 return $this->_label;
25 26 27 28
 * }
 *
 * public function setLabel($value)
 * {
Qiang Xue committed
29
 *	 $this->_label = $value;
30 31 32 33 34 35 36 37 38 39 40 41 42 43
 * }
 * ~~~
 *
 * A property can be accessed like a member variable of an object.
 * Reading or writing a property will cause the invocation of the corresponding
 * getter or setter method. For example,
 *
 * ~~~
 * // equivalent to $label = $object->getLabel();
 * $label = $object->label;
 * // equivalent to $object->setLabel('abc');
 * $object->label = 'abc';
 * ~~~
 *
mdomba (mdlap) committed
44
 * If a property has only a getter method and has no setter method, it is
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
 * considered as *read-only*. In this case, trying to modify the property value
 * will cause an exception.
 *
 * Property names are *case-insensitive*.
 *
 * One can call [[hasProperty]], [[canGetProperty]] and/or [[canSetProperty]]
 * to check the existence of a property.
 *
 * Besides the property feature, the Object class defines a static method
 * [[create]] which provides a convenient alternative way of creating a new
 * object instance.
 *
 * The Object class also defines the [[evaluateExpression]] method so that a PHP
 * expression or callback can be dynamically evaluated within the context of an object.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Object
{
Qiang Xue committed
65 66 67 68 69 70 71
	/**
	 * Constructor.
	 */
	public function __construct()
	{
	}

72
	/**
mdomba (mdlap) committed
73
	 * Returns the value of an object property.
74 75 76 77 78 79 80 81 82 83 84 85 86 87
	 *
	 * Do not call this method directly as it is a PHP magic method that
	 * will be implicitly called when executing `$value = $object->property;`.
	 * @param string $name the property name
	 * @return mixed the property value, event handlers attached to the event,
	 * the named behavior, or the value of a behavior's property
	 * @throws Exception if the property is not defined
	 * @see __set
	 */
	public function __get($name)
	{
		$getter = 'get' . $name;
		if (method_exists($this, $getter)) {
			return $this->$getter();
Qiang Xue committed
88
		} else {
Qiang Xue committed
89
			throw new Exception('Getting unknown property: ' . get_class($this) . '.' . $name);
90 91 92 93
		}
	}

	/**
mdomba (mdlap) committed
94
	 * Sets value of an object property.
95 96 97 98 99 100 101 102 103 104 105 106
	 *
	 * Do not call this method directly as it is a PHP magic method that
	 * will be implicitly called when executing `$object->property = $value;`.
	 * @param string $name the property name or the event name
	 * @param mixed $value the property value
	 * @throws Exception if the property is not defined or read-only.
	 * @see __get
	 */
	public function __set($name, $value)
	{
		$setter = 'set' . $name;
		if (method_exists($this, $setter)) {
Qiang Xue committed
107
			$this->$setter($value);
Qiang Xue committed
108
		} elseif (method_exists($this, 'get' . $name)) {
109
			throw new Exception('Setting read-only property: ' . get_class($this) . '.' . $name);
Qiang Xue committed
110
		} else {
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
			throw new Exception('Setting unknown property: ' . get_class($this) . '.' . $name);
		}
	}

	/**
	 * Checks if the named property is set (not null).
	 *
	 * Do not call this method directly as it is a PHP magic method that
	 * will be implicitly called when executing `isset($object->property)`.
	 *
	 * Note that if the property is not defined, false will be returned.
	 * @param string $name the property name or the event name
	 * @return boolean whether the named property is set (not null).
	 */
	public function __isset($name)
	{
		$getter = 'get' . $name;
		if (method_exists($this, $getter)) { // property is not null
			return $this->$getter() !== null;
Qiang Xue committed
130
		} else {
Qiang Xue committed
131
			return false;
132 133 134 135
		}
	}

	/**
mdomba (mdlap) committed
136
	 * Sets an object property to null.
137 138 139 140 141 142 143 144 145 146 147 148
	 *
	 * Do not call this method directly as it is a PHP magic method that
	 * will be implicitly called when executing `unset($object->property)`.
	 *
	 * Note that if the property is not defined, this method will do nothing.
	 * If the property is read-only, it will throw an exception.
	 * @param string $name the property name
	 * @throws Exception if the property is read only.
	 */
	public function __unset($name)
	{
		$setter = 'set' . $name;
Qiang Xue committed
149
		if (method_exists($this, $setter)) { // write property
150
			$this->$setter(null);
Qiang Xue committed
151
		} elseif (method_exists($this, 'get' . $name)) {
152 153 154 155
			throw new Exception('Unsetting read-only property: ' . get_class($this) . '.' . $name);
		}
	}

Qiang Xue committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
	/**
	 * Calls the named method which is not a class method.
	 * If the name refers to a component property whose value is
	 * an anonymous function, the method will execute the function.
	 *
	 * Do not call this method directly as it is a PHP magic method that
	 * will be implicitly called when an unknown method is being invoked.
	 * @param string $name the method name
	 * @param array $params method parameters
	 * @return mixed the method return value
	 */
	public function __call($name, $params)
	{
		if ($this->canGetProperty($name, false)) {
			$getter = 'get' . $name;
			$func = $this->$getter;
			if ($func instanceof \Closure) {
				return call_user_func_array($func, $params);
			}
		}
		throw new Exception('Unknown method: ' . get_class($this) . "::$name()");
	}

179 180 181 182 183
	/**
	 * Returns a value indicating whether a property is defined.
	 * A property is defined if there is a getter or setter method
	 * defined in the class. Note that property names are case-insensitive.
	 * @param string $name the property name
Qiang Xue committed
184
	 * @param boolean $checkVar whether to treat member variables as properties
185 186 187 188
	 * @return boolean whether the property is defined
	 * @see canGetProperty
	 * @see canSetProperty
	 */
Qiang Xue committed
189
	public function hasProperty($name, $checkVar = true)
190
	{
Qiang Xue committed
191 192
		return $this->canGetProperty($name, false) || $this->canSetProperty($name, false)
			|| $checkVar && property_exists($this, $name);
193 194 195 196 197 198 199
	}

	/**
	 * Returns a value indicating whether a property can be read.
	 * A property can be read if the class has a getter method
	 * for the property name. Note that property name is case-insensitive.
	 * @param string $name the property name
Qiang Xue committed
200
	 * @param boolean $checkVar whether to treat member variables as properties
201 202 203
	 * @return boolean whether the property can be read
	 * @see canSetProperty
	 */
Qiang Xue committed
204
	public function canGetProperty($name, $checkVar = true)
205
	{
Qiang Xue committed
206
		return method_exists($this, 'get' . $name) || $checkVar && property_exists($this, $name);
207 208 209 210 211 212 213
	}

	/**
	 * Returns a value indicating whether a property can be set.
	 * A property can be written if the class has a setter method
	 * for the property name. Note that property name is case-insensitive.
	 * @param string $name the property name
Qiang Xue committed
214
	 * @param boolean $checkVar whether to treat member variables as properties
215 216 217
	 * @return boolean whether the property can be written
	 * @see canGetProperty
	 */
Qiang Xue committed
218
	public function canSetProperty($name, $checkVar = true)
219
	{
Qiang Xue committed
220
		return method_exists($this, 'set' . $name) || $checkVar && property_exists($this, $name);
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
	}

	/**
	 * Evaluates a PHP expression or callback under the context of this object.
	 *
	 * Valid PHP callback can be class method name in the form of
	 * array(ClassName/Object, MethodName), or anonymous function.
	 *
	 * If a PHP callback is used, the corresponding function/method signature should be
	 *
	 * ~~~
	 * function foo($param1, $param2, ..., $object) { ... }
	 * ~~~
	 *
	 * where the array elements in the second parameter to this method will be passed
	 * to the callback as `$param1`, `$param2`, ...; and the last parameter will be the object itself.
	 *
	 * If a PHP expression is used, the second parameter will be "extracted" into PHP variables
	 * that can be directly accessed in the expression.
	 * See [PHP extract](http://us.php.net/manual/en/function.extract.php)
	 * for more details. In the expression, the object can be accessed using `$this`.
	 *
	 * @param mixed $_expression_ a PHP expression or PHP callback to be evaluated.
	 * @param array $_data_ additional parameters to be passed to the above expression/callback.
	 * @return mixed the expression result
	 */
Qiang Xue committed
247
	public function evaluateExpression($_expression_, $_data_ = array())
248 249 250 251
	{
		if (is_string($_expression_)) {
			extract($_data_);
			return eval('return ' . $_expression_ . ';');
Qiang Xue committed
252
		} else {
253 254 255 256 257 258
			$_data_[] = $this;
			return call_user_func_array($_expression_, $_data_);
		}
	}

	/**
Qiang Xue committed
259
	 * Creates a new instance of the calling class.
260 261 262 263
	 *
	 * Parameters passed to this method will be used as the parameters to the object
	 * constructor.
	 *
Qiang Xue committed
264 265 266 267 268 269 270 271 272 273 274
	 * This method does the following steps to create a object:
	 *
	 * - create the object using the PHP `new` operator;
	 * - if [[Yii::objectConfig]] contains the configuration for the object class,
	 *   initialize the object properties with that configuration;
	 * - if the number of the given parameters is more than the number of the parameters
	 *   listed in the object constructor and the last given parameter is an array,
	 *   initialize the object properties using that array;
	 * - call the `init` method of the object if it implements the [[yii\base\Initable]] interface.
	 *
	 * For example,
275 276
	 *
	 * ~~~
Qiang Xue committed
277
	 * class Foo extends \yii\base\Object implements \yii\base\Initable
278
	 * {
Qiang Xue committed
279 280 281 282 283 284 285 286 287
	 *	 public $c;
	 *	 public function __construct($a, $b)
	 *	 {
	 *		 ...
	 *	 }
	 *	 public function init()
	 *	 {
	 *		 ...
	 *	 }
288 289
	 * }
	 *
Qiang Xue committed
290
	 * $model = Foo::newInstance(1, 2, array('c' => 3));
291 292 293
	 * // which is equivalent to the following lines:
	 * $model = new Foo(1, 2);
	 * $model->c = 3;
Qiang Xue committed
294
	 * $model->init();
295 296
	 * ~~~
	 *
Qiang Xue committed
297
	 * @return Object the created object
298 299
	 * @throws Exception if the configuration is invalid.
	 */
Qiang Xue committed
300
	public static function newInstance()
301
	{
Qiang Xue committed
302 303
		$c = get_called_class();
		$class = '\\' . $c;
304 305
		if (($n = func_num_args()) > 0) {
			$args = func_get_args();
Qiang Xue committed
306
			if (is_array($args[$n - 1])) {
307
				$method = new \ReflectionMethod($class, '__construct');
Qiang Xue committed
308 309 310 311
				if ($method->getNumberOfParameters() < $n) {
					// the last EXTRA parameter is a configuration array
					$config = $args[--$n];
					unset($args[$n]);
312 313 314
				}
			}
		}
Qiang Xue committed
315 316 317

		if ($n === 0) {
			$object = new $class;
Qiang Xue committed
318
		} elseif ($n === 1) {
Qiang Xue committed
319
			$object = new $class($args[0]);
Qiang Xue committed
320
		} elseif ($n === 2) {
Qiang Xue committed
321
			$object = new $class($args[0], $args[1]);
Qiang Xue committed
322
		} elseif ($n === 3) {
Qiang Xue committed
323
			$object = new $class($args[0], $args[1], $args[2]);
Qiang Xue committed
324
		} else {
Qiang Xue committed
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
			$r = new \ReflectionClass($class);
			$object = $r->newInstanceArgs($args);
		}

		if (isset(\Yii::$objectConfig[$c])) {
			$config = isset($config) ? array_merge(\Yii::$objectConfig[$c], $config) : \Yii::$objectConfig[$c];
		}

		if (!empty($config)) {
			foreach ($config as $name => $value) {
				$object->$name = $value;
			}
		}

		if ($object instanceof \yii\base\Initable) {
			$object->init();
		}

		return $object;
344 345
	}
}