Create custom Component in Yii2 Application

In this post i will show you how to create a simple custom component in yii2 application.

Yii2 component


Step 1: create a custom file of component in your favourite location . i'm creating it in frontend/components/Custom.php


<?php
namespace app\components;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;

class Custom extends Component
{
public function sayhello()
{
  echo "Welcome to Cutsom Component";
}
}


Step 2
: Add the custom component in your config setting file.

'components' => [
          'custom' => [
            'class' => 'frontend\components\Custom', //your file location
             ],
           ]

Step 3
: All things are done now how to use the component in your controller.

<?php
namespace app\controllers;
use Yii;
class SiteController extends \yii\web\Controller
{
    public function actionIndex()
    {
       Yii::$app->custom->sayhello();
    }
}

I hope you like the post and please comment if you need any help related to this post.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular