PageRenderTime 55ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/demo/yii/base/CComponent.php

https://bitbucket.org/jicheng1014/yii-bootstrap
PHP | 686 lines | 294 code | 30 blank | 362 comment | 82 complexity | d4138ddc750db453268874154ffeacd6 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-3.0, LGPL-2.1, BSD-2-Clause, Apache-2.0
  1. <?php
  2. /**
  3. * This file contains the foundation classes for component-based and event-driven programming.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CComponent is the base class for all components.
  12. *
  13. * CComponent implements the protocol of defining, using properties and events.
  14. *
  15. * A property is defined by a getter method, and/or a setter method.
  16. * Properties can be accessed in the way like accessing normal object members.
  17. * Reading or writing a property will cause the invocation of the corresponding
  18. * getter or setter method, e.g
  19. * <pre>
  20. * $a=$component->text; // equivalent to $a=$component->getText();
  21. * $component->text='abc'; // equivalent to $component->setText('abc');
  22. * </pre>
  23. * The signatures of getter and setter methods are as follows,
  24. * <pre>
  25. * // getter, defines a readable property 'text'
  26. * public function getText() { ... }
  27. * // setter, defines a writable property 'text' with $value to be set to the property
  28. * public function setText($value) { ... }
  29. * </pre>
  30. *
  31. * An event is defined by the presence of a method whose name starts with 'on'.
  32. * The event name is the method name. When an event is raised, functions
  33. * (called event handlers) attached to the event will be invoked automatically.
  34. *
  35. * An event can be raised by calling {@link raiseEvent} method, upon which
  36. * the attached event handlers will be invoked automatically in the order they
  37. * are attached to the event. Event handlers must have the following signature,
  38. * <pre>
  39. * function eventHandler($event) { ... }
  40. * </pre>
  41. * where $event includes parameters associated with the event.
  42. *
  43. * To attach an event handler to an event, see {@link attachEventHandler}.
  44. * You can also use the following syntax:
  45. * <pre>
  46. * $component->onClick=$callback; // or $component->onClick->add($callback);
  47. * </pre>
  48. * where $callback refers to a valid PHP callback. Below we show some callback examples:
  49. * <pre>
  50. * 'handleOnClick' // handleOnClick() is a global function
  51. * array($object,'handleOnClick') // using $object->handleOnClick()
  52. * array('Page','handleOnClick') // using Page::handleOnClick()
  53. * </pre>
  54. *
  55. * To raise an event, use {@link raiseEvent}. The on-method defining an event is
  56. * commonly written like the following:
  57. * <pre>
  58. * public function onClick($event)
  59. * {
  60. * $this->raiseEvent('onClick',$event);
  61. * }
  62. * </pre>
  63. * where <code>$event</code> is an instance of {@link CEvent} or its child class.
  64. * One can then raise the event by calling the on-method instead of {@link raiseEvent} directly.
  65. *
  66. * Both property names and event names are case-insensitive.
  67. *
  68. * CComponent supports behaviors. A behavior is an
  69. * instance of {@link IBehavior} which is attached to a component. The methods of
  70. * the behavior can be invoked as if they belong to the component. Multiple behaviors
  71. * can be attached to the same component.
  72. *
  73. * To attach a behavior to a component, call {@link attachBehavior}; and to detach the behavior
  74. * from the component, call {@link detachBehavior}.
  75. *
  76. * A behavior can be temporarily enabled or disabled by calling {@link enableBehavior}
  77. * or {@link disableBehavior}, respectively. When disabled, the behavior methods cannot
  78. * be invoked via the component.
  79. *
  80. * Starting from version 1.1.0, a behavior's properties (either its public member variables or
  81. * its properties defined via getters and/or setters) can be accessed through the component it
  82. * is attached to.
  83. *
  84. * @author Qiang Xue <qiang.xue@gmail.com>
  85. * @version $Id$
  86. * @package system.base
  87. * @since 1.0
  88. */
  89. class CComponent
  90. {
  91. private $_e;
  92. private $_m;
  93. /**
  94. * Returns a property value, an event handler list or a behavior based on its name.
  95. * Do not call this method. This is a PHP magic method that we override
  96. * to allow using the following syntax to read a property or obtain event handlers:
  97. * <pre>
  98. * $value=$component->propertyName;
  99. * $handlers=$component->eventName;
  100. * </pre>
  101. * @param string $name the property name or event name
  102. * @return mixed the property value, event handlers attached to the event, or the named behavior
  103. * @throws CException if the property or event is not defined
  104. * @see __set
  105. */
  106. public function __get($name)
  107. {
  108. $getter='get'.$name;
  109. if(method_exists($this,$getter))
  110. return $this->$getter();
  111. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  112. {
  113. // duplicating getEventHandlers() here for performance
  114. $name=strtolower($name);
  115. if(!isset($this->_e[$name]))
  116. $this->_e[$name]=new CList;
  117. return $this->_e[$name];
  118. }
  119. else if(isset($this->_m[$name]))
  120. return $this->_m[$name];
  121. else if(is_array($this->_m))
  122. {
  123. foreach($this->_m as $object)
  124. {
  125. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  126. return $object->$name;
  127. }
  128. }
  129. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  130. array('{class}'=>get_class($this), '{property}'=>$name)));
  131. }
  132. /**
  133. * Sets value of a component property.
  134. * Do not call this method. This is a PHP magic method that we override
  135. * to allow using the following syntax to set a property or attach an event handler
  136. * <pre>
  137. * $this->propertyName=$value;
  138. * $this->eventName=$callback;
  139. * </pre>
  140. * @param string $name the property name or the event name
  141. * @param mixed $value the property value or callback
  142. * @return mixed
  143. * @throws CException if the property/event is not defined or the property is read only.
  144. * @see __get
  145. */
  146. public function __set($name,$value)
  147. {
  148. $setter='set'.$name;
  149. if(method_exists($this,$setter))
  150. return $this->$setter($value);
  151. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  152. {
  153. // duplicating getEventHandlers() here for performance
  154. $name=strtolower($name);
  155. if(!isset($this->_e[$name]))
  156. $this->_e[$name]=new CList;
  157. return $this->_e[$name]->add($value);
  158. }
  159. else if(is_array($this->_m))
  160. {
  161. foreach($this->_m as $object)
  162. {
  163. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  164. return $object->$name=$value;
  165. }
  166. }
  167. if(method_exists($this,'get'.$name))
  168. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  169. array('{class}'=>get_class($this), '{property}'=>$name)));
  170. else
  171. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  172. array('{class}'=>get_class($this), '{property}'=>$name)));
  173. }
  174. /**
  175. * Checks if a property value is null.
  176. * Do not call this method. This is a PHP magic method that we override
  177. * to allow using isset() to detect if a component property is set or not.
  178. * @param string $name the property name or the event name
  179. * @return boolean
  180. */
  181. public function __isset($name)
  182. {
  183. $getter='get'.$name;
  184. if(method_exists($this,$getter))
  185. return $this->$getter()!==null;
  186. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  187. {
  188. $name=strtolower($name);
  189. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  190. }
  191. else if(is_array($this->_m))
  192. {
  193. if(isset($this->_m[$name]))
  194. return true;
  195. foreach($this->_m as $object)
  196. {
  197. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  198. return $object->$name!==null;
  199. }
  200. }
  201. return false;
  202. }
  203. /**
  204. * Sets a component property to be null.
  205. * Do not call this method. This is a PHP magic method that we override
  206. * to allow using unset() to set a component property to be null.
  207. * @param string $name the property name or the event name
  208. * @throws CException if the property is read only.
  209. * @return mixed
  210. */
  211. public function __unset($name)
  212. {
  213. $setter='set'.$name;
  214. if(method_exists($this,$setter))
  215. $this->$setter(null);
  216. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  217. unset($this->_e[strtolower($name)]);
  218. else if(is_array($this->_m))
  219. {
  220. if(isset($this->_m[$name]))
  221. $this->detachBehavior($name);
  222. else
  223. {
  224. foreach($this->_m as $object)
  225. {
  226. if($object->getEnabled())
  227. {
  228. if(property_exists($object,$name))
  229. return $object->$name=null;
  230. else if($object->canSetProperty($name))
  231. return $object->$setter(null);
  232. }
  233. }
  234. }
  235. }
  236. else if(method_exists($this,'get'.$name))
  237. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  238. array('{class}'=>get_class($this), '{property}'=>$name)));
  239. }
  240. /**
  241. * Calls the named method which is not a class method.
  242. * Do not call this method. This is a PHP magic method that we override
  243. * to implement the behavior feature.
  244. * @param string $name the method name
  245. * @param array $parameters method parameters
  246. * @return mixed the method return value
  247. */
  248. public function __call($name,$parameters)
  249. {
  250. if($this->_m!==null)
  251. {
  252. foreach($this->_m as $object)
  253. {
  254. if($object->getEnabled() && method_exists($object,$name))
  255. return call_user_func_array(array($object,$name),$parameters);
  256. }
  257. }
  258. if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)
  259. return call_user_func_array($this->$name, $parameters);
  260. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  261. array('{class}'=>get_class($this), '{name}'=>$name)));
  262. }
  263. /**
  264. * Returns the named behavior object.
  265. * The name 'asa' stands for 'as a'.
  266. * @param string $behavior the behavior name
  267. * @return IBehavior the behavior object, or null if the behavior does not exist
  268. */
  269. public function asa($behavior)
  270. {
  271. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  272. }
  273. /**
  274. * Attaches a list of behaviors to the component.
  275. * Each behavior is indexed by its name and should be an instance of
  276. * {@link IBehavior}, a string specifying the behavior class, or an
  277. * array of the following structure:
  278. * <pre>
  279. * array(
  280. * 'class'=>'path.to.BehaviorClass',
  281. * 'property1'=>'value1',
  282. * 'property2'=>'value2',
  283. * )
  284. * </pre>
  285. * @param array $behaviors list of behaviors to be attached to the component
  286. */
  287. public function attachBehaviors($behaviors)
  288. {
  289. foreach($behaviors as $name=>$behavior)
  290. $this->attachBehavior($name,$behavior);
  291. }
  292. /**
  293. * Detaches all behaviors from the component.
  294. */
  295. public function detachBehaviors()
  296. {
  297. if($this->_m!==null)
  298. {
  299. foreach($this->_m as $name=>$behavior)
  300. $this->detachBehavior($name);
  301. $this->_m=null;
  302. }
  303. }
  304. /**
  305. * Attaches a behavior to this component.
  306. * This method will create the behavior object based on the given
  307. * configuration. After that, the behavior object will be initialized
  308. * by calling its {@link IBehavior::attach} method.
  309. * @param string $name the behavior's name. It should uniquely identify this behavior.
  310. * @param mixed $behavior the behavior configuration. This is passed as the first
  311. * parameter to {@link YiiBase::createComponent} to create the behavior object.
  312. * @return IBehavior the behavior object
  313. */
  314. public function attachBehavior($name,$behavior)
  315. {
  316. if(!($behavior instanceof IBehavior))
  317. $behavior=Yii::createComponent($behavior);
  318. $behavior->setEnabled(true);
  319. $behavior->attach($this);
  320. return $this->_m[$name]=$behavior;
  321. }
  322. /**
  323. * Detaches a behavior from the component.
  324. * The behavior's {@link IBehavior::detach} method will be invoked.
  325. * @param string $name the behavior's name. It uniquely identifies the behavior.
  326. * @return IBehavior the detached behavior. Null if the behavior does not exist.
  327. */
  328. public function detachBehavior($name)
  329. {
  330. if(isset($this->_m[$name]))
  331. {
  332. $this->_m[$name]->detach($this);
  333. $behavior=$this->_m[$name];
  334. unset($this->_m[$name]);
  335. return $behavior;
  336. }
  337. }
  338. /**
  339. * Enables all behaviors attached to this component.
  340. */
  341. public function enableBehaviors()
  342. {
  343. if($this->_m!==null)
  344. {
  345. foreach($this->_m as $behavior)
  346. $behavior->setEnabled(true);
  347. }
  348. }
  349. /**
  350. * Disables all behaviors attached to this component.
  351. */
  352. public function disableBehaviors()
  353. {
  354. if($this->_m!==null)
  355. {
  356. foreach($this->_m as $behavior)
  357. $behavior->setEnabled(false);
  358. }
  359. }
  360. /**
  361. * Enables an attached behavior.
  362. * A behavior is only effective when it is enabled.
  363. * A behavior is enabled when first attached.
  364. * @param string $name the behavior's name. It uniquely identifies the behavior.
  365. */
  366. public function enableBehavior($name)
  367. {
  368. if(isset($this->_m[$name]))
  369. $this->_m[$name]->setEnabled(true);
  370. }
  371. /**
  372. * Disables an attached behavior.
  373. * A behavior is only effective when it is enabled.
  374. * @param string $name the behavior's name. It uniquely identifies the behavior.
  375. */
  376. public function disableBehavior($name)
  377. {
  378. if(isset($this->_m[$name]))
  379. $this->_m[$name]->setEnabled(false);
  380. }
  381. /**
  382. * Determines whether a property is defined.
  383. * A property is defined if there is a getter or setter method
  384. * defined in the class. Note, property names are case-insensitive.
  385. * @param string $name the property name
  386. * @return boolean whether the property is defined
  387. * @see canGetProperty
  388. * @see canSetProperty
  389. */
  390. public function hasProperty($name)
  391. {
  392. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  393. }
  394. /**
  395. * Determines whether a property can be read.
  396. * A property can be read if the class has a getter method
  397. * for the property name. Note, property name is case-insensitive.
  398. * @param string $name the property name
  399. * @return boolean whether the property can be read
  400. * @see canSetProperty
  401. */
  402. public function canGetProperty($name)
  403. {
  404. return method_exists($this,'get'.$name);
  405. }
  406. /**
  407. * Determines whether a property can be set.
  408. * A property can be written if the class has a setter method
  409. * for the property name. Note, property name is case-insensitive.
  410. * @param string $name the property name
  411. * @return boolean whether the property can be written
  412. * @see canGetProperty
  413. */
  414. public function canSetProperty($name)
  415. {
  416. return method_exists($this,'set'.$name);
  417. }
  418. /**
  419. * Determines whether an event is defined.
  420. * An event is defined if the class has a method named like 'onXXX'.
  421. * Note, event name is case-insensitive.
  422. * @param string $name the event name
  423. * @return boolean whether an event is defined
  424. */
  425. public function hasEvent($name)
  426. {
  427. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  428. }
  429. /**
  430. * Checks whether the named event has attached handlers.
  431. * @param string $name the event name
  432. * @return boolean whether an event has been attached one or several handlers
  433. */
  434. public function hasEventHandler($name)
  435. {
  436. $name=strtolower($name);
  437. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  438. }
  439. /**
  440. * Returns the list of attached event handlers for an event.
  441. * @param string $name the event name
  442. * @return CList list of attached event handlers for the event
  443. * @throws CException if the event is not defined
  444. */
  445. public function getEventHandlers($name)
  446. {
  447. if($this->hasEvent($name))
  448. {
  449. $name=strtolower($name);
  450. if(!isset($this->_e[$name]))
  451. $this->_e[$name]=new CList;
  452. return $this->_e[$name];
  453. }
  454. else
  455. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  456. array('{class}'=>get_class($this), '{event}'=>$name)));
  457. }
  458. /**
  459. * Attaches an event handler to an event.
  460. *
  461. * An event handler must be a valid PHP callback, i.e., a string referring to
  462. * a global function name, or an array containing two elements with
  463. * the first element being an object and the second element a method name
  464. * of the object.
  465. *
  466. * An event handler must be defined with the following signature,
  467. * <pre>
  468. * function handlerName($event) {}
  469. * </pre>
  470. * where $event includes parameters associated with the event.
  471. *
  472. * This is a convenient method of attaching a handler to an event.
  473. * It is equivalent to the following code:
  474. * <pre>
  475. * $component->getEventHandlers($eventName)->add($eventHandler);
  476. * </pre>
  477. *
  478. * Using {@link getEventHandlers}, one can also specify the excution order
  479. * of multiple handlers attaching to the same event. For example:
  480. * <pre>
  481. * $component->getEventHandlers($eventName)->insertAt(0,$eventHandler);
  482. * </pre>
  483. * makes the handler to be invoked first.
  484. *
  485. * @param string $name the event name
  486. * @param callback $handler the event handler
  487. * @throws CException if the event is not defined
  488. * @see detachEventHandler
  489. */
  490. public function attachEventHandler($name,$handler)
  491. {
  492. $this->getEventHandlers($name)->add($handler);
  493. }
  494. /**
  495. * Detaches an existing event handler.
  496. * This method is the opposite of {@link attachEventHandler}.
  497. * @param string $name event name
  498. * @param callback $handler the event handler to be removed
  499. * @return boolean if the detachment process is successful
  500. * @see attachEventHandler
  501. */
  502. public function detachEventHandler($name,$handler)
  503. {
  504. if($this->hasEventHandler($name))
  505. return $this->getEventHandlers($name)->remove($handler)!==false;
  506. else
  507. return false;
  508. }
  509. /**
  510. * Raises an event.
  511. * This method represents the happening of an event. It invokes
  512. * all attached handlers for the event.
  513. * @param string $name the event name
  514. * @param CEvent $event the event parameter
  515. * @throws CException if the event is undefined or an event handler is invalid.
  516. */
  517. public function raiseEvent($name,$event)
  518. {
  519. $name=strtolower($name);
  520. if(isset($this->_e[$name]))
  521. {
  522. foreach($this->_e[$name] as $handler)
  523. {
  524. if(is_string($handler))
  525. call_user_func($handler,$event);
  526. else if(is_callable($handler,true))
  527. {
  528. if(is_array($handler))
  529. {
  530. // an array: 0 - object, 1 - method name
  531. list($object,$method)=$handler;
  532. if(is_string($object)) // static method call
  533. call_user_func($handler,$event);
  534. else if(method_exists($object,$method))
  535. $object->$method($event);
  536. else
  537. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  538. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  539. }
  540. else // PHP 5.3: anonymous function
  541. call_user_func($handler,$event);
  542. }
  543. else
  544. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  545. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  546. // stop further handling if param.handled is set true
  547. if(($event instanceof CEvent) && $event->handled)
  548. return;
  549. }
  550. }
  551. else if(YII_DEBUG && !$this->hasEvent($name))
  552. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  553. array('{class}'=>get_class($this), '{event}'=>$name)));
  554. }
  555. /**
  556. * Evaluates a PHP expression or callback under the context of this component.
  557. *
  558. * Valid PHP callback can be class method name in the form of
  559. * array(ClassName/Object, MethodName), or anonymous function (only available in PHP 5.3.0 or above).
  560. *
  561. * If a PHP callback is used, the corresponding function/method signature should be
  562. * <pre>
  563. * function foo($param1, $param2, ..., $component) { ... }
  564. * </pre>
  565. * where the array elements in the second parameter to this method will be passed
  566. * to the callback as $param1, $param2, ...; and the last parameter will be the component itself.
  567. *
  568. * If a PHP expression is used, the second parameter will be "extracted" into PHP variables
  569. * that can be directly accessed in the expression. See {@link http://us.php.net/manual/en/function.extract.php PHP extract}
  570. * for more details. In the expression, the component object can be accessed using $this.
  571. *
  572. * @param mixed $_expression_ a PHP expression or PHP callback to be evaluated.
  573. * @param array $_data_ additional parameters to be passed to the above expression/callback.
  574. * @return mixed the expression result
  575. * @since 1.1.0
  576. */
  577. public function evaluateExpression($_expression_,$_data_=array())
  578. {
  579. if(is_string($_expression_) && !function_exists($_expression_))
  580. {
  581. extract($_data_);
  582. return eval('return '.$_expression_.';');
  583. }
  584. else
  585. {
  586. $_data_[]=$this;
  587. return call_user_func_array($_expression_, $_data_);
  588. }
  589. }
  590. }
  591. /**
  592. * CEvent is the base class for all event classes.
  593. *
  594. * It encapsulates the parameters associated with an event.
  595. * The {@link sender} property describes who raises the event.
  596. * And the {@link handled} property indicates if the event is handled.
  597. * If an event handler sets {@link handled} to true, those handlers
  598. * that are not invoked yet will not be invoked anymore.
  599. *
  600. * @author Qiang Xue <qiang.xue@gmail.com>
  601. * @version $Id$
  602. * @package system.base
  603. * @since 1.0
  604. */
  605. class CEvent extends CComponent
  606. {
  607. /**
  608. * @var object the sender of this event
  609. */
  610. public $sender;
  611. /**
  612. * @var boolean whether the event is handled. Defaults to false.
  613. * When a handler sets this true, the rest of the uninvoked event handlers will not be invoked anymore.
  614. */
  615. public $handled=false;
  616. /**
  617. * @var mixed additional event parameters.
  618. * @since 1.1.7
  619. */
  620. public $params;
  621. /**
  622. * Constructor.
  623. * @param mixed $sender sender of the event
  624. * @param mixed $params additional parameters for the event
  625. */
  626. public function __construct($sender=null,$params=null)
  627. {
  628. $this->sender=$sender;
  629. $this->params=$params;
  630. }
  631. }
  632. /**
  633. * CEnumerable is the base class for all enumerable types.
  634. *
  635. * To define an enumerable type, extend CEnumberable and define string constants.
  636. * Each constant represents an enumerable value.
  637. * The constant name must be the same as the constant value.
  638. * For example,
  639. * <pre>
  640. * class TextAlign extends CEnumerable
  641. * {
  642. * const Left='Left';
  643. * const Right='Right';
  644. * }
  645. * </pre>
  646. * Then, one can use the enumerable values such as TextAlign::Left and
  647. * TextAlign::Right.
  648. *
  649. * @author Qiang Xue <qiang.xue@gmail.com>
  650. * @version $Id$
  651. * @package system.base
  652. * @since 1.0
  653. */
  654. class CEnumerable
  655. {
  656. }