能够重用的小的代码模块,不涉及业务逻辑的,用在跟视图相关的方面比较多,一般把Sidebar,Navigation,Page,JS控件(上传,日历)封装成Widget,但Portlet生成的html系统会自动套2层div在html外面,改变了页面样式,可能操作页面样式布局js等失效
下面以一个随机广告图片为例说明Yii中Widget的用法
1. 调用Widget
<?php $this->widget('WidgetName'); ?>
或者
<?php $widget=$this->beginWidget('path.to.WidgetClass'); ?>
...可能会由小物件获取的内容主体...
<?php $this->endWidget(); ?>
也可以传参到Widget类
<?php $this->widget('WidgetName',array('userId'=>$userId)); ?>
参数userId自动映射到Widget类的同名属性,所以在定义Widget时,别忘记了声明该属性。
2. 创建Widget
自定义Widget类要继承CWidget,覆盖方法run
<?php
class BannerMagic extends CWidget {
public function run(){
}
}
或者:
class MyWidget extends CWidget {
public function init() {
// 此方法会被 CController::beginWidget() 调用
}
public function run() {
// 此方法会被 CController::endWidget() 调用
}
}
下面是是BannerMagicWidget实现,存储到protected\components\BannerMagicWidget.php
<?php class BannerMagicWidget extends CWidget {
public function run() {
$random = rand(1,3);
if ($random == 1) {
$advert = "advert1.jpg";
} else if ($random == 2) {
$advert = "advert2.jpg";
} else {
$advert = "advert3.jpg";
}
$this->render('bannermagic',array(
"advert"=>$advert,
));
}
}
对应的view文件可能的内容如下:
<img src="images/adverts/<?php echo $advert; ?>" alt="whatever" />
存储到protected\components\views\bannermagic.php
3. 调用该Widget
<?php $this->widget('BannerMagicWidget'); ?>
CPortlet继承自CWidget。这意味portlet作为一个widget,可以在用widget()方法在页面中插入.它覆盖了CPortlet
类的 renderContent()
方法等
protected\components\RecentComments.php (1)
<?php
Yii::import('zii.widgets.CPortlet');
class RecentComments extends CPortlet
{
public $title='Recent Comments'; //title
public $maxComments=10;
public function getRecentComments()
{
return Comment::model()->findRecentComments($this->maxComments);
}
protected function renderContent()
{
$this->render('recentComments'); //模板文件
}
}
protected\components\views\recentComments.php 模板文件(2)
<ul>
<?php foreach($this->getRecentComments() as $comment): ?>
<li><?php echo $comment->authorLink; ?> on
<?php echo CHtml::link(CHtml::encode($comment->post->title), $comment->getUrl()); ?>
</li>
<?php endforeach; ?>
</ul>
调用方法 (3)
<?php $this->widget('RecentComments', array('maxComments'=>Yii::app()->params['recentCommentCount'],
)); ?>