How to create custom component in Yii2.0 Framework

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

Application compoent syntax

Yii::$app->componentID

sample Core Application Components

Yii::$app->db
Yii::$app->cache
Yii::$app->request
Yii::$app->session
Yii::$app->mailer
etc

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.

<?php
namespace app\components;

use yii\base\Component;

class MessageComponent extends Component{
	public $content;
	
	public function init(){
		parent::init();
		$this->content= 'Hello Yii 2.0';
	}
	
	public function display($content=null){
		if($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 Yii Custom Component Function

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

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