X
    Categories: YII

Create Custom Component in YII 2

Create Custom Component in YII 2

Custom Component is help us to use application in our own style. We need to create and set a global variable to access both the controller and view pages. Yii Normally we will access yii components like this way. For example Yii::$app->db, Yii::$app->user, Yii::$app->session, Yii::$app->assetManager etc. Here Yii allowing us to create custom components also, Lets see how to Create Custom Component in Yii 2 and access it in anywhere in the application.

I have table called Settings which contains the information about site like logo, site_name, site_slogan, site_title, copy_rights, support_email.

I can give these details in statically in main.php file and access it, but for my future use we are accessing this details dynamically.

Step 1 : Create Custom Component Class
Step 2 : Map with config components array
Step 3 : Access Component.

Step 1 : Create Custom Component Class

I have created components folder inside my backend folder and create SettingsComponent.php file inside components folder.

<?php
namespace app\components;

use yii\base\Component;
use yii\db\Query;
use app\models\Setting;

class SettingsComponent extends Component{

    public function siteSettings($content=null){
        return Setting::find()->one();  
    }
    
}

Step 2 : Map with config components array

Open backend/config/main.php and add Mapping code under conponents array.

'components' => [
    'siteSettings' => [
           'class' => 'app\components\SettingsComponent',
        ],
],

Now we can access Yii::$app->siteSettings expression.


Step 3 : Access Component

Lets see how to access a method siteSettings which is inside SettingsComponent class.

$siteSettings =  Yii::$app->siteSettings->siteSettings();

It will return the result of “Setting::find()->one()” query.

Logo => $siteSettings['logo'];
site_name => $siteSettings['site_name'];
site_slogan => $siteSettings['site_slogan'];
site_title => $siteSettings['site_title'];
copy_rights => $siteSettings['copy_rights'];

Thats all, Now you can access your component globally.
If you like this article don’t forget to share and comment.
Happy Coding!!!

Marimuthu: