Yii框架开发项目实战技巧

YII模块IP白名单设置,增加安全性

$config['modules']['gii'] = [
     'class' => 'yii\gii\Module',
     'allowedIPs' => ['127.0.0.1', '::1','10.10.1.*'], 
];
$config['modules']['debug'] = [
    'class' => 'yii\debug\Module',
    'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.33.1'],
];

防止SQL和Script注入

use yii\helpers\Html;
use yii\helpers\HtmlPurifier;
echo Html::encode($string); //可以原样显示代码  
echo HtmlPurifier::process($string);  //可以过滤掉代码

设置点击下载链接

public function actionDownload(){
    return \Yii::$app->response->setDownloadHeaders("http://xxx.com/xxx.rar");
    //return \Yii::$app->response->sendFile("./file.rar");
}

密码比对,Model中配置相关rules

    public function rules()
    {
        return [
            [['password','repeat_password'], 'required'],
            ['repeat_password', 'compare', 'compareAttribute' => 'password', 'operator' => '===','message'=>'两次密码不一致,请重新输入。'],
            [['created_time', 'last_modified_time'], 'safe'],
            [['mobile'], 'string', 'max' => 12],
        ];
    }

多表联查中,自定义ActiveForm字段的排序

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = User::find();
        $query->joinWith(['userAccount account']);
        $query->joinWith(['businessCardRecord card']);

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'register_time' => SORT_DESC,
                ]
            ],
        ]);
        
        //自定义要进行排序的字段,支持多表
        $dataProvider->setSort([
            'attributes' => [
                'user_id',
                'status',
                'user_level',
                'register_time',
                'register_source',
                'mobile' => [
                    'asc' => ['account.mobile' => SORT_ASC],
                    'desc' => ['account.mobile' => SORT_DESC],
                    'label' => 'mobile'
                ],
                'name' => [
                    'asc' => ['card.name' => SORT_ASC],
                    'desc' => ['card.name' => SORT_DESC],
                    'label' => 'name'
                ],
            ]
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        if (isset($params['keyword'])) {
            $query->filterWhere(['like', 'card.user_id', $params['keyword']])
                ->orFilterWhere(['like', 'account.mobile', $params['keyword']])
                ->orFilterWhere(['like', 'card.name', $params['keyword']]);
        }

        return $dataProvider;
    }