Create Widget In Yii

I learned "How To Create Widget" in yii. Just i created welcome widget for my application.

What is widget

Widget is a small gadget.An application or a component of an interface, that enables a user to perform a function or access a service.

Create Widget Class


//Welcomewidget .php
<?php
class Welcomewidget extends CWidget{
    public $message;
    public function init(){
        $this->message=array(
            'Hai',
            'Yess It Is',
            'How are you?',
            'How is going life?'
        );
        
    }
    public function run(){
        $id=rand(0,3);
        $this->render("displaymessage",array('id'=>$id));    
    }
}
?>
Create one class "Welcomewidget" with extends CWidget. Then i created one global variable for this widget. that is called "$message". I stored display messages in this variables in init() method. When run this class It called "displaymessage" file. It should be inside "Views" folder and i display message inside view file.

Create Widget View


//displaymessage .php
<div  style="float: right;
         padding-right: 50px;
         padding-top: 12px;
         font-size: 30px;">
<?php
    echo $this->message[$id];
?>
</div>
This "displaymessage" file called by "Welcomewidget" class. Here i get and display the message using global $message variables and random number to get message from array.

Call Widget function


    
<?php $this->widget('Welcomewidget'); ?>
In my "site/layout/main.php", I included this code. It is displaying message on every new page load. Widget is a powerful and simple option in YII.