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

You are viewing revision #1 of this wiki article.
This is the latest version of this article.

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

0 0
5 followers
Viewed: 46 911 times
Version: Unknown (update)
Category: How-tos
Written by: Deepak Pradhan
Last updated by: Deepak Pradhan
Created on: Oct 18, 2014
Last updated: 10 years ago
Update Article

Revisions

View all history

Related Articles