Component in yii 2

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

step2:
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

eg:

‘components’ => [

‘mycomponent’ => [

‘class’ => ‘app\components\MyComponent’,

],
]

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()
{
Yii::$app->mycomponent->welcome();
}

}
or use it in view

mycomponent->welcome();

?>

Leave a Reply

Your email address will not be published. Required fields are marked *