Yii2, Create and use components

April 20, 2017 43 Yehor Rykhnov

An example of creating and working with your own components in Yii2.

If you need to call the same method or class from different parts of the code, then the best thing for these purposes is working with the component

Creating your component in Yii2

First, create the "components" folder in the root of your application (app/components (for basic) and app/frontend|backend|common/components for advanced). Next, we create a class for a component with its own namespace and extend from the Component class. For example, create the MyComponent componen (app/components/MyComponent.php):

<?php

namespace app\components;

use yii\base\Component;

class MyComponent extends Component {

    public function mySuperMethod() {
        //your code
        //return ;
    }

}

Next, you need to add the component to the configuration file app/config/web.php:

<?php

$params = require(__DIR__ . '/params.php');
$config = [
    //...

    'components' => [
        // ...
        'mycomponent' => [
            'class' => 'app\components\MyComponent'
        ]
    ],

   //...

Now we can use the component in the application code.

Using your component in Yii2

Component has been created, now you can use it with help one line of code:

Yii::$app->mycomponent->mySuperMethod();