Home > Article > PHP Framework > How to customize yii components
The following is an example of how to create a custom component in Yii2.0
The first step: under common Create components folder.
Step 2: Create a custom component in the newly created components folder, such as: ReadHttpHeader.php, the code is as follows:
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; } } } } } }
Note: 'common' is already in common/config/ Bootstrap.php has defined aliases and can be used directly.
Step 3: Open common/config/main.php(main-local.php) and add your components to the configuration file.
<?php return [ 'components' => [ 'ReadHttpHeader' => [ 'class' => 'common\components\ReadHttpHeader' ], ], ];
Step 4: Now our component method can be called by all controllers. For example, we now load our component ReadHttpHeader in our base controller (BaseController), and other controllers inherit it. Our base controller.
<?php namespace frontend\controllers; use Yii; use yii\web\Controller; class BaseController extends Controller { protected $session = false; public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], ]; } public function init() { parent::init(); // IP essential for prelim DDoS check if (!$this->cgS('UC-SEC.1a')) { $ip = Yii::$app->ReadHttpHeader->RealIP(); echo $ip; } } }
The above is a custom component to obtain the real IP. Take this as an example to illustrate the process of the custom component.
PHP Chinese website has a large number of free Yii introductory tutorials, everyone is welcome to learn!
The above is the detailed content of How to customize yii components. For more information, please follow other related articles on the PHP Chinese website!