Home > Backend Development > PHP Tutorial > Yii中创建自己的Widget实例_PHP

Yii中创建自己的Widget实例_PHP

WBOY
Release: 2016-05-28 11:49:36
Original
870 people have browsed it

本文实例讲述了Yii中创建自己的Widget实现方法。分享给大家供大家参考,具体如下:

这里以一个随机广告图片为例说明Yii中Widget的用法

1. 调用Widget

代码如下:

widget('WidgetName'); ?>


或者

<&#63;php $widget=$this->beginWidget('path.to.WidgetClass'); &#63;>
...可能会由小物件获取的内容主体...
<&#63;php $this->endWidget(); &#63;>

Copy after login

也可以传参到Widget类

<&#63;php $userId = 1; &#63;>
<&#63;php $this->widget('WidgetName',array('userId'=>$userId)); &#63;>

Copy after login

参数userId自动映射到Widget类的同名属性,所以在定义Widget时,别忘记了声明该属性。

2. 创建Widget

自定义Widget类要继承CWidget,覆盖方法run

<&#63;php
class BannerMagic extends CWidget {
  public function run(){
  }
}

Copy after login

或者:

class MyWidget extends CWidget {
  public function init() {
    // 此方法会被 CController::beginWidget() 调用
  }
   public function run() {
    // 此方法会被 CController::endWidget() 调用
  }
}

Copy after login

下面是是BannerMagicWidget实现

<&#63;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,
   ));
  }
}

Copy after login

存储到protected\components\BannerMagicWidget.php

对应的view文件可能的内容如下:

代码如下:

whatever


存储到protected\components\views\bannermagic.php

3. 调用该Widget

代码如下:

widget('BannerMagicWidget'); ?>

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template