Difference Between A Widget And A Component?

Hello everyone,

I am new to yii and I have watched the instructional videos on this site and I am also in the process of reading through The Definitive Guide. I just read about widgets and components, but I am confused about when each should be used.

I am thinking that a widget is a kind of like a self contained controller with its own directory structure for its own views. I am not sure at all what a component is after reading the guide. Could someone give an example of when you created a widget and another example of a time when you created a component. I guess a short widget vs. component explanation would do me good.

Thanks

I’m new myself, but from what I understand so far, widgets are reusable chunks of code that you use in view files. I picture them the same as widgets in android (calendar, contacts, etc.)

Components are extensions of core application. For instance, database connection is a component (Yii::app()->db) and so is a user (Yii::app()->user).

I may be wrong though, since I just started learning Yii.

In my opinion, a Widget is a special Component (CWidgets extends CBaseController which extends CComponent).

You can consider CComponent as the base class for Yii providing some functionnality regarding getters/setters, events and behaviors.

A widget is a Controller that normally renders a view for the widget. You can use the widget in views. The widget is supposed to provide some reuseable functionnality.

‘haosmark’ is talking about ‘CApplicationComponent’ which is another kind of Component that is directly available as a singleton in the application. The application component is instantiated only when it is first used (or when the configuration says to preload it). This allows you to define a lot of application components with little impact on the performance as long as you do not use them.

CWidget’s and CApplicationComponent’s can both receive default configurations settings from the ‘config.php’ file. CApplicationComponents are handy because you can use extended ApplicationComponents without having to change your application to refer to the new class.

I have some ApplicationComponents that are implemented as a proxy and one particular one even using RBAC information to select the right class instance to use for the user.

One of the ApplicationComponents I use is an ‘SmsSender’. The SMS sender sends an SMS to a given destination. The Sender depends on the service chosen for the target web site, so the class used depends on the web site’s configuration.

I have created a widget for ‘on/off’ buttons. The widget has three views available one of which is chosen through it’s configuration. Depending on the view, the “on/off button” is either a checkbox, alternating images (similar to X,v) or a Yes/No slider. That ‘on/off’ widget is itself referenced in another widget to show/hide a content block through an on/off slider.

Hopefully these examples make things clearer for you.