Write & use a custom Component in Yii2.0

You are viewing revision #8 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#7)next (#9) »

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

namespace app\controllers;
use Yii;

class TestController extends \yii\web\Controller
    public function actionWelcome()


Thanks. happy coding... Sirin K


Hire Yii developer