Dorokhov.codes

Yii2: about widgets

Yii2: about widgets

Yii2 is a framework with an MVC architecture. Logic, views and controllers are separated here. Widget is a component that directly relates to the view component.

Widget example:

namespace app\widgets;

use yii\base\Widget;
use yii\helpers\Html;

class HelloWidget extends Widget
{
    public $message;

    public function init()
    {
        parent::init();
        if ($this->message === null) {
            $this->message = 'Hello World';
        }
    }

    public function run()
    {
        return Html::encode($this->message);
    }
}

To use this widget, simply insert the following code in a view:

<?php
use app\components\HelloWidget;
?>
<?= HelloWidget::widget(['message' => 'Good morning']) ?>