Want create site? Find Free WordPress Themes and plugins.

Hi there, Today I would like to write a simple tutorial on creating custom Component in Yii2 and I will show you how to use created component in your application.

Here is the simple steps, just follow the step at the end you will have your first custom component.


Make a folder named “components” in your project root folder.


Crate a file with desired component name inside components folder and copy past the below code.

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


Add your component inside the config/web.php file

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


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()

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – we are here to solve your problems.

Did you find apk for android? You can find new Free Android Games and apps.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)

Posted by Editorial Staff