Best Practice For Writing Code For Widgets.

Hello,

Is it good or bad thing if I will use queries to database or will track request parameters inside code of widget?

Here is example about what I mean:


class MyWidget extends Widget 

{

    public function run()

    {

        $id = Yii::$app->request->get('item_id')

        if ($id) {

            $item = Item::findOne($id);

            return $this->renderFile(

	        '@frontend/views/widgets/MyWidget', 

		['item' => $item]

	    );

        }

    }

}

I think that is not well, but I encountered an opposite opinion.

Thank you.

By definition Widgets are self-contained building blocks for your views, a way to combine complex logic, display, and functionality into a single component. A widget:

  • May contain advanced PHP programming

  • Is typically configurable

  • Is often provided data to be displayed

  • Returns HTML to be shown within the context of the view

Thank you for reply.

I’ve read it before. And I was confused by several phrases because of English is not my native language.

Where is edge of advanced programming? I think "advanced" is a wide term.

Is that mean well if I will interact with database, file system, network or something else inside widget code?

And I don’t see an approach mentioned before inside built-in widgets.

In normal MVC, views should have minima PHP codes aka simple programming!

No! Widgets does not manipulate data from source, you do the play and feed data to a widget!

Thank you for answer