Yii2如何在Controller中包含一个php文件

Rav*_*ndr 2 php yii2

在我的Yii2框架工作项目中,我想要包含一个php文件.该文件包含两个函数文件名"encryptdecrypt.php"并将其保存在common\extension文件夹中

<?
    public function encryptIt( $q ) {
        $cryptKey  = 'OrangeOnlineMedia';
        $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
        return( $qEncoded );
    }

    public function decryptIt( $q ) {
        $cryptKey  = 'OrangeOnlineMedia';
        $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
        return( $qDecoded );
    }

    ?>
Run Code Online (Sandbox Code Playgroud)

我在控制器页面中包含此行("CustomersController")

页面顶部包括使用此行

$encFile =Yii::getAlias('@common'). '\extensions\encryptdecrypt.php';
require_once($encFile);
Run Code Online (Sandbox Code Playgroud)

并在下面的动作代码中使用该功能

public function actionCreate()
{
    $model = new Customers();

    if ($model->load(Yii::$app->request->post()) ) {

        $model->password=encryptIt($model->password);            
        if($model->created_date==null)
        {
          $model->created_date=date('y-m-d') ; 
        }
        $model->save();
        return $this->redirect(['view', 'id' => $model->customer_id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

这里我收到以下错误"调用未定义的函数backend\controllers\encryptIt()"

谢谢

Tou*_*afi 5

Yii2使用PSR-4 AutoLoader规则,所以先保存Security.php

common\extensions文件夹中,然后打开Security.php并在其中创建类.

<?php

namespace common\extensions;

class Security {

    public function encrypt(){
    // todo
    }

    public function decrypt(){
    // todo
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在你的CustomersController行动中Create使用它像这样:

public function actionCreate()
{
    $model = new Customers();

    if ($model->load(Yii::$app->request->post()) ) {
        $security = new \common\extensions\Security(); // <-- Create Object Here
        $model->password= $security->encrypt($model->password);            
        if($model->created_date==null)
        {
          $model->created_date=date('y-m-d') ; 
        }
        $model->save();
        return $this->redirect(['view', 'id' => $model->customer_id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

在Yii2中BTW你也可以像这样生成安全密码哈希: Yii::$app->security->generatePasswordHash($password);