Create your own widget instance _php instance in Yii

Source: Internet
Author: User
Tags php class yii

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.