The example in this article describes the implementation method of creating your own Widget 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 code The code is as follows:widget('WidgetName'); ?>
or
<?php $widget=$this->beginWidget('path.to.WidgetClass'); ?> ...可能会由小物件获取的内容主体... <?php $this->endWidget(); ?>
You can also pass parameters to the Widget class
<?php $userId = 1; ?> <?php $this->widget('WidgetName',array('userId'=>$userId)); ?>
The parameter userId is automatically mapped to the property of the same name of the Widget class, so don’t forget to declare this property when defining the Widget.
2. Create Widget
The custom Widget class must inherit CWidget and override the method run
<?php class BannerMagic extends CWidget { public function run(){ } }
or:
class MyWidget extends CWidget { public function init() { // 此方法会被 CController::beginWidget() 调用 } public function run() { // 此方法会被 CController::endWidget() 调用 } }
The following is the implementation of BannerMagicWidget
<?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, )); } }
Store to protectedcomponentsBannerMagicWidget.php
The possible contents of the corresponding view file are as follows:
Copy code The code is as follows:
Store to protectedcomponentsviewsbannermagic.php
3. Call the Widget
Copy 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.