Yii 2.0: Write & use a custom Component in Yii2.0


This is a simple example in Yii2.0 to understand how you can write a custom component and use it inside your app.(basic template)

Step1:Make a folder named "components" in your project root folder.

write your custom component inside components folder eg:MyComponent.php

namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
class MyComponent extends Component
 public function welcome()
  echo "Hello..Welcome to MyComponent";

Step3:Add your component inside the config/web.php file


'components' => [
         'mycomponent' => [
            'class' => 'app\components\MyComponent',

Step4:You are done!. Now you can use your component method "welcome" inside any of your app controller actions. eg:controllers/TestController.php

namespace app\controllers;
use Yii;
class TestController extends \yii\web\Controller
    public function actionWelcome()

Thanks. happy coding... Sirin K


Total 4 comments

#19587 report it
Yii3 at 2015/09/18 08:18am
Get module component

I found the solution for how to access module component.

If you have placed your components in modules then

// Current Module object 
  $module = Yii::$app->controller->module;
#19551 report it
Yii3 at 2015/09/04 03:05am
How to use module components and aliases?

I have created components in module and i want to use it. How can i do it?

'modules'   => [
          'v1' => [
            'class' => 'api\modules\v1\v1',
            'helper' => [
              'class' => 'api\modules\v1\components\Helper',

In my controller i am accessing it as


How to use module aliases?

#18769 report it
Abed Alzain at 2015/01/03 01:13am

Thanks great tut

#18430 report it
vikashg at 2014/10/28 10:08am
make components in side models in yii 2

how make components in side models folder and how to use

Leave a comment

Please to leave your comment.

Write new article