Yii Framework 2 : Create Custom Component

Yii2.0 framework having default application components and it is giving different type services. For example ‘urlManager’ component, ‘db’ component etc. Every application component has an uniqueID and will call through expression format. We can create Application components like global or local variables.

Syntax And Core Components In Yii2.0

Application compoent syntax


sample Core Application Components


Create Your Own Component In Yii2.0

Create a folder named “components” in the project root directory. Now create one class ‘MessageComponent’ with extends class ‘Component’ inside the components folder. Using this component, we will display message. Please see the below code to create a custom component class.

namespace app\components;

use yii\base\Component;

class MessageComponent extends Component{
    public $content;
    public function init(){
        $this->content= 'Hello Yii 2.0';
    public function display($content=null){
            $this->content= $content;
        echo Html::encode($this->content);

Config Component In Yii2.0

We have to register ‘MessageComponent’ by configuring the yii\base\Application::$components property inside the config/web.php file (application configurations).

'components' => [
    'message' => [
        'class' => 'app\components\MessageComponent',

Now we can access this component using ‘Yii::$app()->message’ expression.

Call Custom Component Function In Yii2.0

Using configured ‘message’ component, we can call the method inside the ‘MessageComponent’.

Yii::$app->message->display('I am Yii2.0 Programmer');


Leave a Reply

Your email address will not be published. Required fields are marked *