下面是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 [ 'components' => [ 'ReadHttpHeader' => [ 'class' => 'commoncomponentsReadHttpHeader' ], ], ]; 第四步:现在我们的组件方法可以被所有控制器调用,比如我们现在在我们的基础控制器(BaseController)中加载我们的组件ReadHttpHeader ,其他控制器都继承我们的基础控制器 <?php namespace frontendcontrollers; use Yii; use yiiwebController; class BaseController extends Controller { protected $session = false; public function actions() { return [ 'error' => [ 'class' => 'yiiwebErrorAction', ], ]; } public function init() { parent::init(); // IP essential for prelim DDoS check if (!$this->cgS('UC-SEC.1a')) { $ip = Yii::$app->ReadHttpHeader->RealIP(); echo $ip; } } }
以上就是Yii2.0 创建一个自定义组件方法的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor