翻譯自:http://www.yiiframework.com/wiki/760/yii-2-0-write-use-a-custom-component-in-yii2-0-advanced-template/php
簡單模版中添加自定義組件:http://www.yiiframework.com/wiki/747/write-use-a-custom-component-in-yii2-0/mysql
咱們實現的是添加一個讀取真實IP的組件,下面是詳細步驟:sql
1. 在項目根目錄的common目錄中新建components目錄。swift
2. 在components目錄裏新建ReadHttpHeader.php。這個是組件要實現的功能。yii2
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.phpapp
添加下面的代碼yii
<?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. 調用自定義組件。this
打開任意一個Controller文件,好比我打開的是backend\controllers\SiteController.php。spa
在合適的地方調用組件。翻譯
public function actionIndex() { //自定義組件 echo Yii::$app->ReadHttpHeader->RealIP(); return $this->render('index'); }
完。