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 a component in your application.
Here are the simple steps, just follow the step at the end you will have your first custom component.
Step1:
Make a folder named “components” in your project root folder.
step2:
Crate a file with desired component name inside components folder and copy past the below code. Example – MyComponent.php
1 2 3 4 5 6 7 8 9 10 11 |
namespace app\components; use Yii; use yii\base\Component; use yii\base\InvalidConfigException; class MyComponent extends Component { public function welcome() { echo "Welcome to MyComponent"; } } |
Step3:
Add your component inside the config/web.php file
eg:
1 2 3 4 5 |
'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
1 2 3 4 5 6 7 8 9 |
namespace app\controllers; use Yii; class TestController extends \yii\web\Controller { public function actionWelcome() { Yii::$app->mycomponent->welcome(); } } |
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.