Home > Backend Development > PHP Tutorial > Create your own Widget instance in Yii

Create your own Widget instance in Yii

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-29 09:07:40
Original
857 people have browsed it

The example in this article describes how to create your own Widget implementation in Yii. Share it with everyone for your reference, the details are as follows:

Here is a random advertising image as an example to illustrate the usage of Widget in Yii

1. Call Widget

Copy the code The code is as follows:

widget('WidgetName'); ?>


or

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

Copy after login

can also be passed to the Widget class

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

Copy after login

The parameter userId is automatically mapped to the property of the same name of the Widget class, so when defining the Widget , don't forget to declare this attribute.

2. Create Widget

To inherit CWidget, override the method run

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

Copy after login

or:

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

Copy after login

The following is the BannerMagicWidget implementation

<&#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

stored in protectedcomponentsBannerMagicW idget.php

corresponding The possible content of the view file is as follows:

Copy the code The code is as follows:

Create your own in Yii Widget instance


is stored in protectedcomponentsviewsbannermagic.php

3. Call the Widget

Copy the code The code is as follows:

widget('BannerMagicWidget'); ? >

I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.

The above introduces how to create your own Widget instance in Yii, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
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