I have read (all) the tutorials on components and I’m still a little unsure when to use CComponent Vs. CApplicationComponent.

AFAIK, CApplicationComponent is normally "setup" in the main.config and is lazy loaded and initialized when Yii::componentName is called.

CComponent needs to be initialized the traditional way using the constructor and is called using Yii::createComponent(‘componentName’).

Can someone please provide concrete examples of when to use one versus the other.

Also, is there a benefit to calling Yii::createComponent (CComponent ) over $myComponent = new MyComponent(). As far as I can see, the latter will provide code completion (using an IDE) whilst the former will not.



Hi Matt,

Both CComponent and CApplicationComponent seems to be low-level internal, base component classes. Why and what for do you want to use them, instead of using some more specific, sophisticated classes that are based upon those two base classes?




CComponent is a class that provides getter/setter functionality + events. If you need something like this, extend from there.

CApplicationComponent is a more specialised CComponent that can be used if you want to create your own application component (Who’d have thunk it? ;) ). As you already found out, it has an init() method that is automatically called, whenever the application component is (lazy) loaded and has the configuration applied.

That’s about all there is to say, no mysteries…

Maybe this also helps you:

How to create "hello world" component - Yii Framework Forum

public function myblabla()

? :] LOL! :]

The main benefit in practical terms is that classes that extend CApplicationComponent can be accessed via:

$property = Yii::app()->yourClassAlias->property;

$response = Yii::app()->yourClassAlias->method();

You just need to configure it in main.php like this:







Now you can globally access that object as a singleton that only gets created once. …So that’s something you can’t do with classes that extend CComponent.