Yii 2.0: Yii 2.0: Write & use a custom Component in Yii2.0 (Advanced Template)

5 followers

This is an extension to Yii 2.0: Write & use a custom Component in Yii2.0 for Advanced Template

Step1: Create a folder named "components" under 'common' in your project root folder.

step2: Write your custom component inside components folder eg: ReadHttpHeader.php

namespace common\components;
 
use Yii;
use yii\base\Component;
 
class ReadHttpHeader extends Component {
 
    public  function RealIP()
    {
        $ip = false;
 
        $seq = array('HTTP_CLIENT_IP',
                  'HTTP_X_FORWARDED_FOR'
                  , 'HTTP_X_FORWARDED'
                  , 'HTTP_X_CLUSTER_CLIENT_IP'
                  , 'HTTP_FORWARDED_FOR'
                  , 'HTTP_FORWARDED'
                  , 'REMOTE_ADDR');
 
        foreach ($seq as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                        return $ip;
                    }
                }
            }
        }
    }
 
}

Note: 'common' is defined alias in common/config/bootstrap.php

Step3: Add your component inside the config/main-local.php file (for now!)

<?php
 
return [
          'components' => [
                    'db' => [
                              'class' => 'yii\db\Connection',
                              ...
                              'charset' => 'utf8',
                    ],
                    'mailer' => [
                              'class' => 'yii\swiftmailer\Mailer',
                               ...
                    ],
                    'ReadHttpHeader' => [
                              'class' => 'common\components\ReadHttpHeader'
                    ],
          ],
];

Step 4: Now this component's methods can be consumed inside any app controller or base controller. Below is my Base Controller called 'AController', from which other controllers may extend

<?php
 
namespace frontend\controllers;
 
use Yii;
use yii\web\Controller;
 
class AController extends Controller {
 
    protected $session = false;
 
    public function actions() {
        return [
                  'error' => [
                            'class' => 'yii\web\ErrorAction',
                  ],
        ];
    }
 
    public function init() {
 
        parent::init();
 
        // IP essential for prelim DDoS check
        if (!$this->cgS('UC-SEC.1a')) {
            $ip = Yii::$app->ReadHttpHeader->RealIP();
            echo $ip;
        }
    }
 
}

O/P is : 174.106.72.79

Total 1 comment

#19849 report it
omeraslam at 2016/05/06 05:36am
omer aslam

the config-local.php file you mentioned is the one inside the common folder, means common\config\config-local.php

Leave a comment

Please to leave your comment.

Write new article