PageRenderTime 58ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/base/CComponent.php

https://github.com/balor/yiicms
PHP | 659 lines | 263 code | 30 blank | 366 comment | 65 complexity | 78a686782b3c1d30750460059b199ccf MD5 | raw file
Possible License(s): BSD-3-Clause
  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-2010 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. * Starting from version 1.0.2, 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: CComponent.php 1858 2010-03-05 16:47:11Z qiang.xue $
  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 the property name or event name
  102. * @return mixed the property value, event handlers attached to the event, or the named behavior (since version 1.0.2)
  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 the property name or the event name
  141. * @param mixed the property value or callback
  142. * @throws CException if the property/event is not defined or the property is read only.
  143. * @see __get
  144. */
  145. public function __set($name,$value)
  146. {
  147. $setter='set'.$name;
  148. if(method_exists($this,$setter))
  149. return $this->$setter($value);
  150. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  151. {
  152. // duplicating getEventHandlers() here for performance
  153. $name=strtolower($name);
  154. if(!isset($this->_e[$name]))
  155. $this->_e[$name]=new CList;
  156. return $this->_e[$name]->add($value);
  157. }
  158. else if(is_array($this->_m))
  159. {
  160. foreach($this->_m as $object)
  161. {
  162. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  163. return $object->$name=$value;
  164. }
  165. }
  166. if(method_exists($this,'get'.$name))
  167. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  168. array('{class}'=>get_class($this), '{property}'=>$name)));
  169. else
  170. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  171. array('{class}'=>get_class($this), '{property}'=>$name)));
  172. }
  173. /**
  174. * Checks if a property value is null.
  175. * Do not call this method. This is a PHP magic method that we override
  176. * to allow using isset() to detect if a component property is set or not.
  177. * @param string the property name or the event name
  178. * @since 1.0.1
  179. */
  180. public function __isset($name)
  181. {
  182. $getter='get'.$name;
  183. if(method_exists($this,$getter))
  184. return $this->$getter()!==null;
  185. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  186. {
  187. $name=strtolower($name);
  188. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  189. }
  190. else
  191. return false;
  192. }
  193. /**
  194. * Sets a component property to be null.
  195. * Do not call this method. This is a PHP magic method that we override
  196. * to allow using unset() to set a component property to be null.
  197. * @param string the property name or the event name
  198. * @throws CException if the property is read only.
  199. * @since 1.0.1
  200. */
  201. public function __unset($name)
  202. {
  203. $setter='set'.$name;
  204. if(method_exists($this,$setter))
  205. $this->$setter(null);
  206. else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  207. unset($this->_e[strtolower($name)]);
  208. else if(method_exists($this,'get'.$name))
  209. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  210. array('{class}'=>get_class($this), '{property}'=>$name)));
  211. }
  212. /**
  213. * Calls the named method which is not a class method.
  214. * Do not call this method. This is a PHP magic method that we override
  215. * to implement the behavior feature.
  216. * @param string the method name
  217. * @param array method parameters
  218. * @return mixed the method return value
  219. * @since 1.0.2
  220. */
  221. public function __call($name,$parameters)
  222. {
  223. if($this->_m!==null)
  224. {
  225. foreach($this->_m as $object)
  226. {
  227. if($object->getEnabled() && method_exists($object,$name))
  228. return call_user_func_array(array($object,$name),$parameters);
  229. }
  230. }
  231. throw new CException(Yii::t('yii','{class} does not have a method named "{name}".',
  232. array('{class}'=>get_class($this), '{name}'=>$name)));
  233. }
  234. /**
  235. * Returns the named behavior object.
  236. * The name 'asa' stands for 'as a'.
  237. * @param string the behavior name
  238. * @return IBehavior the behavior object, or null if the behavior does not exist
  239. * @since 1.0.2
  240. */
  241. public function asa($behavior)
  242. {
  243. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  244. }
  245. /**
  246. * Attaches a list of behaviors to the component.
  247. * Each behavior is indexed by its name and should be an instance of
  248. * {@link IBehavior}, a string specifying the behavior class, or an
  249. * array of the following structure:
  250. * <pre>
  251. * array(
  252. * 'class'=>'path.to.BehaviorClass',
  253. * 'property1'=>'value1',
  254. * 'property2'=>'value2',
  255. * )
  256. * </pre>
  257. * @param array list of behaviors to be attached to the component
  258. * @since 1.0.2
  259. */
  260. public function attachBehaviors($behaviors)
  261. {
  262. foreach($behaviors as $name=>$behavior)
  263. $this->attachBehavior($name,$behavior);
  264. }
  265. /**
  266. * Detaches all behaviors from the component.
  267. * @since 1.0.2
  268. */
  269. public function detachBehaviors()
  270. {
  271. if($this->_m!==null)
  272. {
  273. foreach($this->_m as $name=>$behavior)
  274. $this->detachBehavior($name);
  275. $this->_m=null;
  276. }
  277. }
  278. /**
  279. * Attaches a behavior to this component.
  280. * This method will create the behavior object based on the given
  281. * configuration. After that, the behavior object will be initialized
  282. * by calling its {@link IBehavior::attach} method.
  283. * @param string the behavior's name. It should uniquely identify this behavior.
  284. * @param mixed the behavior configuration. This is passed as the first
  285. * parameter to {@link YiiBase::createComponent} to create the behavior object.
  286. * @return IBehavior the behavior object
  287. * @since 1.0.2
  288. */
  289. public function attachBehavior($name,$behavior)
  290. {
  291. if(!($behavior instanceof IBehavior))
  292. $behavior=Yii::createComponent($behavior);
  293. $behavior->setEnabled(true);
  294. $behavior->attach($this);
  295. return $this->_m[$name]=$behavior;
  296. }
  297. /**
  298. * Detaches a behavior from the component.
  299. * The behavior's {@link IBehavior::detach} method will be invoked.
  300. * @param string the behavior's name. It uniquely identifies the behavior.
  301. * @return IBehavior the detached behavior. Null if the behavior does not exist.
  302. * @since 1.0.2
  303. */
  304. public function detachBehavior($name)
  305. {
  306. if(isset($this->_m[$name]))
  307. {
  308. $this->_m[$name]->detach($this);
  309. $behavior=$this->_m[$name];
  310. unset($this->_m[$name]);
  311. return $behavior;
  312. }
  313. }
  314. /**
  315. * Enables all behaviors attached to this component.
  316. * @since 1.0.2
  317. */
  318. public function enableBehaviors()
  319. {
  320. if($this->_m!==null)
  321. {
  322. foreach($this->_m as $behavior)
  323. $behavior->setEnabled(true);
  324. }
  325. }
  326. /**
  327. * Disables all behaviors attached to this component.
  328. * @since 1.0.2
  329. */
  330. public function disableBehaviors()
  331. {
  332. if($this->_m!==null)
  333. {
  334. foreach($this->_m as $behavior)
  335. $behavior->setEnabled(false);
  336. }
  337. }
  338. /**
  339. * Enables an attached behavior.
  340. * A behavior is only effective when it is enabled.
  341. * A behavior is enabled when first attached.
  342. * @param string the behavior's name. It uniquely identifies the behavior.
  343. * @since 1.0.2
  344. */
  345. public function enableBehavior($name)
  346. {
  347. if(isset($this->_m[$name]))
  348. $this->_m[$name]->setEnabled(true);
  349. }
  350. /**
  351. * Disables an attached behavior.
  352. * A behavior is only effective when it is enabled.
  353. * @param string the behavior's name. It uniquely identifies the behavior.
  354. * @since 1.0.2
  355. */
  356. public function disableBehavior($name)
  357. {
  358. if(isset($this->_m[$name]))
  359. $this->_m[$name]->setEnabled(false);
  360. }
  361. /**
  362. * Determines whether a property is defined.
  363. * A property is defined if there is a getter or setter method
  364. * defined in the class. Note, property names are case-insensitive.
  365. * @param string the property name
  366. * @return boolean whether the property is defined
  367. * @see canGetProperty
  368. * @see canSetProperty
  369. */
  370. public function hasProperty($name)
  371. {
  372. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  373. }
  374. /**
  375. * Determines whether a property can be read.
  376. * A property can be read if the class has a getter method
  377. * for the property name. Note, property name is case-insensitive.
  378. * @param string the property name
  379. * @return boolean whether the property can be read
  380. * @see canSetProperty
  381. */
  382. public function canGetProperty($name)
  383. {
  384. return method_exists($this,'get'.$name);
  385. }
  386. /**
  387. * Determines whether a property can be set.
  388. * A property can be written if the class has a setter method
  389. * for the property name. Note, property name is case-insensitive.
  390. * @param string the property name
  391. * @return boolean whether the property can be written
  392. * @see canGetProperty
  393. */
  394. public function canSetProperty($name)
  395. {
  396. return method_exists($this,'set'.$name);
  397. }
  398. /**
  399. * Determines whether an event is defined.
  400. * An event is defined if the class has a method named like 'onXXX'.
  401. * Note, event name is case-insensitive.
  402. * @param string the event name
  403. * @return boolean whether an event is defined
  404. */
  405. public function hasEvent($name)
  406. {
  407. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  408. }
  409. /**
  410. * Checks whether the named event has attached handlers.
  411. * @param string the event name
  412. * @return boolean whether an event has been attached one or several handlers
  413. */
  414. public function hasEventHandler($name)
  415. {
  416. $name=strtolower($name);
  417. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  418. }
  419. /**
  420. * Returns the list of attached event handlers for an event.
  421. * @param string the event name
  422. * @return CList list of attached event handlers for the event
  423. * @throws CException if the event is not defined
  424. */
  425. public function getEventHandlers($name)
  426. {
  427. if($this->hasEvent($name))
  428. {
  429. $name=strtolower($name);
  430. if(!isset($this->_e[$name]))
  431. $this->_e[$name]=new CList;
  432. return $this->_e[$name];
  433. }
  434. else
  435. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  436. array('{class}'=>get_class($this), '{event}'=>$name)));
  437. }
  438. /**
  439. * Attaches an event handler to an event.
  440. *
  441. * An event handler must be a valid PHP callback, i.e., a string referring to
  442. * a global function name, or an array containing two elements with
  443. * the first element being an object and the second element a method name
  444. * of the object.
  445. *
  446. * An event handler must be defined with the following signature,
  447. * <pre>
  448. * function handlerName($event) {}
  449. * </pre>
  450. * where $event includes parameters associated with the event.
  451. *
  452. * This is a convenient method of attaching a handler to an event.
  453. * It is equivalent to the following code:
  454. * <pre>
  455. * $component->getEventHandlers($eventName)->add($eventHandler);
  456. * </pre>
  457. *
  458. * Using {@link getEventHandlers}, one can also specify the excution order
  459. * of multiple handlers attaching to the same event. For example:
  460. * <pre>
  461. * $component->getEventHandlers($eventName)->insertAt(0,$eventHandler);
  462. * </pre>
  463. * makes the handler to be invoked first.
  464. *
  465. * @param string the event name
  466. * @param callback the event handler
  467. * @throws CException if the event is not defined
  468. * @see detachEventHandler
  469. */
  470. public function attachEventHandler($name,$handler)
  471. {
  472. $this->getEventHandlers($name)->add($handler);
  473. }
  474. /**
  475. * Detaches an existing event handler.
  476. * This method is the opposite of {@link attachEventHandler}.
  477. * @param string event name
  478. * @param callback the event handler to be removed
  479. * @return boolean if the detachment process is successful
  480. * @see attachEventHandler
  481. */
  482. public function detachEventHandler($name,$handler)
  483. {
  484. if($this->hasEventHandler($name))
  485. return $this->getEventHandlers($name)->remove($handler)!==false;
  486. else
  487. return false;
  488. }
  489. /**
  490. * Raises an event.
  491. * This method represents the happening of an event. It invokes
  492. * all attached handlers for the event.
  493. * @param string the event name
  494. * @param CEvent the event parameter
  495. * @throws CException if the event is undefined or an event handler is invalid.
  496. */
  497. public function raiseEvent($name,$event)
  498. {
  499. $name=strtolower($name);
  500. if(isset($this->_e[$name]))
  501. {
  502. foreach($this->_e[$name] as $handler)
  503. {
  504. if(is_string($handler))
  505. call_user_func($handler,$event);
  506. else if(is_callable($handler,true))
  507. {
  508. if(is_array($handler))
  509. {
  510. // an array: 0 - object, 1 - method name
  511. list($object,$method)=$handler;
  512. if(is_string($object)) // static method call
  513. call_user_func($handler,$event);
  514. else if(method_exists($object,$method))
  515. $object->$method($event);
  516. else
  517. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  518. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  519. }
  520. else // PHP 5.3: anonymous function
  521. call_user_func($handler,$event);
  522. }
  523. else
  524. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  525. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  526. // stop further handling if param.handled is set true
  527. if(($event instanceof CEvent) && $event->handled)
  528. return;
  529. }
  530. }
  531. else if(YII_DEBUG && !$this->hasEvent($name))
  532. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  533. array('{class}'=>get_class($this), '{event}'=>$name)));
  534. }
  535. /**
  536. * Evaluates a PHP expression or callback under the context of this component.
  537. *
  538. * Valid PHP callback can be class method name in the form of
  539. * array(ClassName/Object, MethodName), or anonymous function (only available in PHP 5.3.0 or above).
  540. *
  541. * If a PHP callback is used, the corresponding function/method signature should be
  542. * <pre>
  543. * function foo($param1, $param2, ..., $component) { ... }
  544. * </pre>
  545. * where the array elements in the second parameter to this method will be passed
  546. * to the callback as $param1, $param2, ...; and the last parameter will be the component itself.
  547. *
  548. * If a PHP expression is used, the second parameter will be "extracted" into PHP variables
  549. * that can be directly accessed in the expression. See {@link http://us.php.net/manual/en/function.extract.php PHP extract}
  550. * for more details. In the expression, the component object can be accessed using $this.
  551. *
  552. * @var mixed a PHP expression or PHP callback to be evaluated.
  553. * @param array additional parameters to be passed to the above expression/callback.
  554. * @return mixed the expression result
  555. * @since 1.1.0
  556. */
  557. public function evaluateExpression($_expression_,$_data_=array())
  558. {
  559. if(is_string($_expression_))
  560. {
  561. extract($_data_);
  562. return eval('return '.$_expression_.';');
  563. }
  564. else
  565. {
  566. $_data_[]=$this;
  567. return call_user_func_array($_expression_, $_data_);
  568. }
  569. }
  570. }
  571. /**
  572. * CEvent is the base class for all event classes.
  573. *
  574. * It encapsulates the parameters associated with an event.
  575. * The {@link sender} property describes who raises the event.
  576. * And the {@link handled} property indicates if the event is handled.
  577. * If an event handler sets {@link handled} to true, those handlers
  578. * that are not invoked yet will not be invoked anymore.
  579. *
  580. * @author Qiang Xue <qiang.xue@gmail.com>
  581. * @version $Id: CComponent.php 1858 2010-03-05 16:47:11Z qiang.xue $
  582. * @package system.base
  583. * @since 1.0
  584. */
  585. class CEvent extends CComponent
  586. {
  587. /**
  588. * @var object the sender of this event
  589. */
  590. public $sender;
  591. /**
  592. * @var boolean whether the event is handled. Defaults to false.
  593. * When a handler sets this true, the rest uninvoked handlers will not be invoked anymore.
  594. */
  595. public $handled=false;
  596. /**
  597. * Constructor.
  598. * @param mixed sender of the event
  599. */
  600. public function __construct($sender=null)
  601. {
  602. $this->sender=$sender;
  603. }
  604. }
  605. /**
  606. * CEnumerable is the base class for all enumerable types.
  607. *
  608. * To define an enumerable type, extend CEnumberable and define string constants.
  609. * Each constant represents an enumerable value.
  610. * The constant name must be the same as the constant value.
  611. * For example,
  612. * <pre>
  613. * class TextAlign extends CEnumerable
  614. * {
  615. * const Left='Left';
  616. * const Right='Right';
  617. * }
  618. * </pre>
  619. * Then, one can use the enumerable values such as TextAlign::Left and
  620. * TextAlign::Right.
  621. *
  622. * @author Qiang Xue <qiang.xue@gmail.com>
  623. * @version $Id: CComponent.php 1858 2010-03-05 16:47:11Z qiang.xue $
  624. * @package system.base
  625. * @since 1.0
  626. */
  627. class CEnumerable
  628. {
  629. }