Yii2 Component基类分析
2015-08-27 10:35
555 查看
Yii2 Component类是整个Yii2 框架的基础,它重写了从Object类继承而来的getter和setter方法,主要添加的以下属性:
1. getter不止可以获取类中的属性,同时可以获取行为中的属性。
2. setter除了可以设置属性外,还可以设置事件和行为:
3. 覆写了__call方法,使从Component继承的类可以直接使用行为中的方法。
4. 其他的如isset, unset, canGetProperty, canSetProperty等辅助方法都对行为(Behavior)做了支持。
1. getter不止可以获取类中的属性,同时可以获取行为中的属性。
public function __get($name) { $getter = 'get' . $name; if (method_exists($this, $getter)) { // read property, e.g. getName() return $this->$getter(); } else { // behavior property $this->ensureBehaviors(); foreach ($this->_behaviors as $behavior) { if ($behavior->canGetProperty($name)) { return $behavior->$name; } } } if (method_exists($this, 'set' . $name)) { throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name); } else { throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name); } }
2. setter除了可以设置属性外,还可以设置事件和行为:
public function __set($name, $value) { $setter = 'set' . $name; if (method_exists($this, $setter)) { // set property $this->$setter($value); return; } elseif (strncmp($name, 'on ', 3) === 0) { // on event: attach event handler $this->on(trim(substr($name, 3)), $value); return; } elseif (strncmp($name, 'as ', 3) === 0) { // as behavior: attach behavior $name = trim(substr($name, 3)); $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value)); return; } else { // behavior property $this->ensureBehaviors(); foreach ($this->_behaviors as $behavior) { if ($behavior->canSetProperty($name)) { $behavior->$name = $value; return; } } } if (method_exists($this, 'get' . $name)) { throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name); } else { throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name); } }
3. 覆写了__call方法,使从Component继承的类可以直接使用行为中的方法。
public function __call($name, $params) { $this->ensureBehaviors(); foreach ($this->_behaviors as $object) { if ($object->hasMethod($name)) { return call_user_func_array([$object, $name], $params); } } throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()"); }
4. 其他的如isset, unset, canGetProperty, canSetProperty等辅助方法都对行为(Behavior)做了支持。
相关文章推荐
- PHP 5.4中的traits特性
- PHP使用PHPExcel导出,导入数据总结
- PHP5.3 goto操作符介绍
- 辛星浅析php中coment技术的实现
- 制作yaffs2文件系统简程
- PHP新的垃圾回收机制:Zend GC详解
- Ubuntu配置FTP,SSH,NFS服务
- php trim()函数
- phpcms如何使用推荐位调用自定义字段
- PHP正则表达式及实例
- php实现验证码的识别(初级篇)
- php给图片添加文字水印方法汇总
- php大力力 [026节] php开发状态要随时做好整理工作
- php大力力 [025节] 来不及学习和分类的,大力力认为有价值的一些技术文章合集(大力力二叔公)(2015-08-27)
- php大力力 [024节]PHP中的字符串连接操作(2015-08-27)
- php大力力 [023节]CREATE TABLE创建新表sql写字段备注(2015-08-27)
- php大力力 [022节]php编程要有一种态度:渴望遇见麻烦
- php给图片添加文字水印方法汇总
- PHP生成随机密码方法汇总
- php页面,mysql数据库转utf-8乱码,utf-8编码问题总结