php 在yii2中放置beforesave函数的位置,如何在控制器中访问

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29158109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:16:36  来源:igfitidea点击:

where to put beforesave function in yii2, how to access in controller

phpauthenticationyii2

提问by randawahyup

i want make signup function in my app, how to create hash password using yii2.

我想在我的应用程序中创建注册功能,如何使用 yii2 创建哈希密码。

this is my user.php

这是我的 user.php

<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\base\Security;
use yii\web\IdentityInterface;
/**
 * This is the model class for table "users".
 *
 * @property string $userid
 * @property string $username
 * @property string $password
 */

class User extends ActiveRecord  implements IdentityInterface
    {

        public static function tableName()
        {
            return 'users';
        }

        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                [['username', 'password', 'password_hash','auth_key', 'password_reset_token'], 'required'],
                [['username', 'password'], 'string', 'max' => 45],
                [['auth_key'], 'string', 'max' => 32],
                [['password_reset_token', 'password_hash'], 'string', 'max' => 255],
                [['username'], 'unique']
            ];
        }

        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
            return [
                'id' => 'ID',
                'username' => 'Username',
                'password' => 'Password',
                'password_hash' => 'Password hash',
                'auth_key' => 'Auth Key',
                'password_reset_token' => 'Password Reset Token',
            ];
        }    
        /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
            /**
         * @inheritdoc
         */


        public static function findIdentity($id)
        {
            return static::findOne($id);
        }


        public static function findIdentityByAccessToken($token, $type = null)
        {
              return static::findOne(['access_token' => $token]);
        }


        /**
         * Finds user by username
         *
         * @param  string      $username
         * @return static|null
         */
        public static function findByUsername($username)
        {
            return static::findOne(['username' => $username]);
        }

        /**
         * Finds user by password reset token
         *
         * @param  string      $token password reset token
         * @return static|null
         */
        public static function findByPasswordResetToken($token)
        {
            $expire = \Yii::$app->params['user.passwordResetTokenExpire'];
            $parts = explode('_', $token);
            $timestamp = (int) end($parts);
            if ($timestamp + $expire < time()) {
                // token expired
                return null;
            }

            return static::findOne([
                'password_reset_token' => $token
            ]);
        }

        /**
         * @inheritdoc
         */
        public function getId()
        {
            return $this->getPrimaryKey();
        }

        /**
         * @inheritdoc
         */
        public function getAuthKey()
        {
            return $this->auth_key;
        }

        /**
         * @inheritdoc
         */
        public function validateAuthKey($authKey)
        {
            return $this->getAuthKey() === $authKey;
        }

        /**
         * Validates password
         *
         * @param  string  $password password to validate
         * @return boolean if password provided is valid for current user
         */
        public function validatePassword($password)
        {
            return $this->password === $password;//sha1($password);
        }

        /**
         * Generates password hash from password and sets it to the model
         *
         * @param string $password
         */
        public function setPassword($password)
        {
            $this->password_hash = Yii::$app->getSecurity()->generatePasswordHash($password);//Security::generatePasswordHash($password);
        }

        /**
         * Generates "remember me" authentication key
         */
        public function generateAuthKey()
        {
            $this->auth_key = Security::generateRandomKey();
        }

        /**
         * Generates new password reset token
         */
        public function generatePasswordResetToken()
        {
            $this->password_reset_token = Security::generateRandomKey() . '_' . time();
        }

        /**
         * Removes password reset token
         */
        public function removePasswordResetToken()
        {
            $this->password_reset_token = null;
        }

    }

this is my UserController.php

这是我的 UserController.php

public function actionCreate()
    {
$model = new User;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
}

i want use setPassword function in user model, where i must put beforesave function and i need to change actionCreate function ?

我想在用户模型中使用 setPassword 函数,我必须在其中放置 beforesave 函数,我需要更改 actionCreate 函数?

thank's for help.

感谢帮助。

回答by arogachev

You should place it in your model, because this method is located in yii\db\BaseActiveRecord. Override it as mentioned in official docs:

你应该把它放在你的模型中,因为这个方法位于yii\db\BaseActiveRecord. 如官方文档中所述覆盖它:

/**
 * @inheritdoc
 */
public function beforeSave($insert)
{
    if (parent::beforeSave($insert)) {
        // Place your custom code here

        return true;
    } else {
        return false;
    }
}

Official docs:

官方文档: