Home >> Latest Articles >> How to Create Custom Component in Yii Framework

How to Create Custom Component in Yii Framework

Yii framework having default application components and it is giving different type services.

#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.

You may also like - Yii Interview Questions Answers
Yii framework: Types of Components in Yii2:
  1. Core Components
  2. Custom Components
1. Core Components
Yii::$app->componentID;

Core Application Components Examples

Yii::$app->db; //DB Component
Yii::$app->cache; //Cache Component
Yii::$app->request;
Yii::$app->session;
Yii::$app->mailer;
2. Custom Components
  1. Create a folder named "components" in the project common folder.
  2. Now create one class FullStackTutorialsComponent with extends class ‘Component’ inside the components folder.Using this component, we will display message.
  3. Please see the below code to create a custom component class.
  4. namespace common\components;
    
    use Yii;
    use yii\base\Component;
    use yii\helpers\Html;
    
    class FullStackTutorialsComponent extends Component{
     public $content;
     
     public function init(){
    	parent::init();
    	$this->content= 'Hello This is Default Message of Custom Component in Yii2';
     }
     
     public function display($content=null){
    	if($content!=null){
    		$this->content= $content;
    	}
    	echo Html::encode($this->content);
     }
     
    }
    
    
  5. Config Component In Yii2 We have to register 'FullStackTutorialsComponent' inside the common/config/main.php or common/config/main-local.php file.
  6.  'components' => [
           'fullstacktutorials' => [
             'class' => 'common\components\FullStackTutorialsComponent',
           ],
    ],
    
  7. Call Yii2 Custom Component Function in Yii Framework
  8. Now we can access this component using ‘Yii::$app->fullstacktutorials’ expression
    echo Yii::$app->fullstacktutorials->display('Congrats! This is your custom Component.');
    
You may also like - PHP Interview Questions Answers
Full Stack Tutorials

Author @FullStackTutorials | View all Articles