The examples in this article describe how to create your own widget implementations in Yii. Share to everyone for your reference, as follows:
Here is an example of the use of widgets in Yii using a random ad image
1. Calling the Widget
Copy the Code code as follows:
<?php $this->widget (' widgetname ');?>
Or
<?php $widget = $this->beginwidget (' Path.to.WidgetClass '); Content bodies that may be acquired by small objects ... <?php $this->endwidget ();?>
You can also send a reference to the Widget class
<?php $userId = 1;? ><?php $this->widget (' Widgetname ', Array (' userId ' = $userId));?>
The parameter userid is automatically mapped to a property of the same name as the Widget class, so when you define the widget, don't forget to declare the property.
2. Create Widgets
Custom widget class to inherit CWidget, override method Run
<?phpclass Bannermagic extends CWidget {public function run () { }}
Or:
Class Mywidget extends CWidget {public function init () { //This method is 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, ));} }
Store to protected\components\bannermagicwidget.php
The possible contents of the corresponding view file are as follows:
Copy the Code code as follows:
Create your own widget instance in "alt=" Yii "/>
Store to protected\components\views\bannermagic.php
3. Call the Widget
Copy the Code code as follows:
<?php $this->widget (' Bannermagicwidget ');?>
It is hoped that this article is helpful to the PHP program design based on YII framework.
The above introduces Yii to create their own widget instances, including aspects of the content, I hope to be interested in PHP tutorial friends helpful.