This article is an example of how to create your own widget implementation in Yii. Share to everyone for your reference, specific as follows:
Here is an example of a random ad picture illustrating the use of widgets in Yii
1. Invoke Widget
Copy Code code as follows:
<?php $this->widget (' widgetname ');?>
Or
<?php $widget = $this->beginwidget (' Path.to.WidgetClass ');?>
... Content bodies that may be fetched by small objects ...
<?php $this->endwidget ();?>
You can also pass the widget class
<?php $userId = 1;?>
<?php $this->widget (' Widgetname ', Array (' UserId ' => $userId));?>
Parameter UserID automatically maps to the same name as the Widget class, so don't forget to declare the widget when you define it.
2. Create Widget
Custom widget class to inherit CWidget, 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 ()
}
Here 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";
} els e {
$advert = "advert3.jpg";
}
$this->render (' bannermagic ', Array (
"advert" => $advert)
;
}
Stored to protected\components\bannermagicwidget.php
The possible contents of the corresponding view file are as follows:
Copy Code code as follows:
Stored to protected\components\views\bannermagic.php
3. Invoke the Widget
Copy Code code as follows:
<?php $this->widget (' Bannermagicwidget ');?>
I hope this article will help you with the PHP program design based on the YII framework.