Home  >  Article  >  PHP Framework  >  Is it reasonable for Yii to place data operations on widgets?

Is it reasonable for Yii to place data operations on widgets?

(*-*)浩
(*-*)浩Original
2019-12-14 10:10:431809browse

Is it reasonable for Yii to place data operations on widgets?

Some people will choose to make multiple layouts and switch layouts in different places, but this does not maximize the reusability of the code and is not flexible enough. There is a very convenient mechanism in Yii to solve this problem, that is - widget, which is a widget. (Recommended learning: yii framework)

yii has some built-in widgets, which are placed under web.widgets and zii.widgets, such as our commonly used CLinkPager, You can take a look at CMenu.

To extend widget yourself, according to the introduction in the manual, you need to inherit CWidget and override the run() method. Let's start extending the first widget:

Create the widget storage directory: Create the directory widgets under application (default is protected) to store widget classes, and then create the widgets.views directory for Stores the view file of the widget.

Create the widget class: Create a file named TestWidget.php under application.widgets. The naming is not too particular, ensure uniqueness, just know the name. Add the following code inside:

class TestWidget extends CWidget
{
    public $datetime = ''; 

    public function run()
    {
        $datetime = empty($this->datetime) ? date('Y-m-d H:i:s') : $this->datetime;
        $this->render('test', array('datetime'=>$datetime));
    }
}

Explain this code: According to the rules, the class name TestWidget is the same as the file name TestWidget.php. The class TestWidget needs to inherit CWidget and then rewrite the run() method. This method will be called when the widget is rendered.

Call the $this->render() method in the run() method to render the test view, and pass the variable $datetime to the view (see controller view rendering). You can query the database, perform various operations, and pass the results of operations into the view.

The above is the detailed content of Is it reasonable for Yii to place data operations on widgets?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn