This article describes the creation of your own Widget implementation method in Yii. Share it for your reference, as follows:
Here we use a random advertising image as an example to illustrate the usage of Widget in Yii
1. Call Widget
or
<?php $widget=$this->beginWidget(''); ?> ...Content body that may be obtained by small objects... <?php $this->endWidget(); ?>
You can also pass the 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 the property when defining a Widget.
2. Create a Widget
Custom Widget class must inherit CWidget and override method run
<?php class BannerMagic extends CWidget { public function run(){ } }
or:
class MyWidget extends CWidget { public function init() { // This method will be called by CController::beginWidget() } public function run() { // This method will be called by CController::endWidget() } }
The following is the BannerMagicWidget implementation
<?php class BannerMagicWidget extends CWidget { public function run() { $random = rand(1,3); if ($random == 1) { $advert = ""; } else if ($random == 2) { $advert = ""; } else { $advert = ""; } $this->render('bannermagic',array( "advert"=>$advert, )); } }
Store to protected\components\
The possible contents of the corresponding view file are as follows:
Store to protected\components\views\
3. Call the Widget
I hope that this article will be helpful to everyone's PHP programming based on the Yii framework.