Home >Backend Development >PHP Tutorial >Create your own Widget instance in Yii
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'); ?>
<?php $widget=$this->beginWidget('path.to.WidgetClass'); ?> ...可能会由小物件获取的内容主体... <?php $this->endWidget(); ?>
can also be passed 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 when defining the Widget , don't forget to declare this attribute.
2. Create Widget
To inherit CWidget, 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 BannerMagicWidget implementation
<?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, )); } }
stored in protectedcomponentsBannerMagicW idget.php
corresponding The possible content of the view file is as follows:
Copy the code The code is as follows:
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.