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'); }
完。