Saturday, 1 October 2016

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.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts