Pergunta

Is it considered bad practice to call a Yii widget such as

$this->widget('application.extensions.qrcode.QRCodeGenerator', array(
    'data' => $this->data,
    'subfolderVar' => true,
    'matrixPointSize' => 5,
));

from within a component or model? if yes, why so?

Foi útil?

Solução

It is bad practice to call widgets in controllers/ models etc because widgets are view objects;

It is against MVC principles. MVC is designed based on certain rules and if followed gives significant benefits

Read on Yii's own explanation of how they have implemented MVC to understand better

To put it simply Yii is an MVC framework; Having three layer architecture where

**Model** layer represents  consists of application data, business rules, logic and functions

**view** layer represents  any output representation of information such a widget

**Controller** layer accepts input and converts it to commands for the model or view

The purpose of using three distinct layers is design concept called Separation of Concerns (Soc).

In lay terms basically the designer/UI/UX/frontend and application programmer can work independent of each other if concerns are separated. The designer needs to worry how the data is to be rendered not how or where it came from ( i.e. design and use widgets) , the app programmer needs only think about business logic not worry how it needs to presented

When you mix view objects in models this get broken.

There are numerous other advantages in maintaining this separation including easier debugging (you know where what is) simpler testing ( units are smaller and simpler), better project management(different teams work on different parts of the application without breaking each others work), looser coupling( I can for example easily use the same model functions for an API or a mobile app), code reusability, etc;

Note This is not comprehensive, This is just to give you an idea; The full list of pros and cons of different design patterns could fill many books

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top