【译】Yii2 0 高级模版编写使用自定义组件(component)

原文:http://www.yiiframework.com/wiki/760/yii-2-0-write-use-a-custom-component-in-yii2-0-advanced-template

简单模版中添加自定义组件:http://www.yiiframework.com/wiki/747/write-use-a-custom-component-in-yii2-0/

我们实现的是添加一个读取真实IP的组件,下面是详细步骤:

1. 在项目根目录的common目录中新建components目录。
2. 在components目录里新建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;
                    }
                }
            }
        }
    }
 
}
复制代码
3. 引入组件。打开common/config/main-local.php

添加下面的代码

<?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=yii2_demo',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'tablePrefix' => 'au_',
        ],
         //  新添加的
        'ReadHttpHeader' => [
            'class' => 'common\components\ReadHttpHeader'
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
    ],
];
复制代码
4. 调用自定义组件。

打开任意一个Controller文件,比如我打开的是backend\controllers\SiteController.php。

在合适的地方调用组件。

    public function actionIndex()
    {
         //自定义组件
        echo Yii::$app->ReadHttpHeader->RealIP();
        
        return $this->render('index');
    }
复制代码

转载于:https://juejin.im/post/5aa7705d6fb9a028c675614f

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值