Home > php教程 > PHP开发 > body text

Yii2.0 creates a custom component method

黄舟
Release: 2017-01-03 09:38:27
Original
1179 people have browsed it

下面是Yii2.0如何创建一个自定义组件的实例

第一步:在common下创建components文件夹

第二步: 在新建的components文件夹中创建一个自定义组件 比如:ReadHttpHeader.php,代码如下

) as $ip) {
                    if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                        return $ip;
                    }
                }
            }
        }
    }
 
}

注意: 'common' 已经在 common/config/bootstrap.php定义好了别名,可以直接使用

第三步:打开common/config/main.php(main-local.php) 在配置文件中添加你的组件

<?php
 
return [
          &#39;components&#39; => [
                    &#39;ReadHttpHeader&#39; => [
                              &#39;class&#39; => &#39;commoncomponentsReadHttpHeader&#39;
                    ],
          ],
 ];

第四步:现在我们的组件方法可以被所有控制器调用,比如我们现在在我们的基础控制器(BaseController)中加载我们的组件ReadHttpHeader ,其他控制器都继承我们的基础控制器

<?php
 
namespace frontendcontrollers;
 
use Yii;
use yiiwebController; 
class BaseController extends Controller {
 
    protected $session = false;
 
    public function actions() {
        return [
                  &#39;error&#39; => [
                            &#39;class&#39; => &#39;yiiwebErrorAction&#39;,
                  ],
        ];
    }
 
    public function init() {
 
        parent::init();
 
        // IP essential for prelim DDoS check
        if (!$this->cgS(&#39;UC-SEC.1a&#39;)) {
            $ip = Yii::$app->ReadHttpHeader->RealIP();
            echo $ip;
        }
    }
 
}
Copy after login

以上就是Yii2.0 创建一个自定义组件方法的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!