YII2 管理账户

1 创建数据迁移

创建数据迁移
yii migrate/create admin
生成文件
/console/migrates/m170522_141237_admin.php

<?php
use yii\db\Migration;
class m170522_141237_admin extends Migration
{
    const TBLNAME = '{{%admin}}';
    public function safeUp()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci AUTO_INCRMENT=500 ENGINE=InnoDB';
        }
        $this->createTable(self::TBLNAME, [
            'id' => $this->primaryKey(),
            'username' => $this->string()->notNull()->unique(),
            'email' => $this->string()->notNull()->unique(),
            'password_hash' => $this->string()->notNull(),
            'auth_key' => $this->string(32)->notNull(),
            'password_reset_token' => $this->string()->unique(),
            'status' => $this->smallInteger()->notNull()->defaultValue(10),
            'created_at' => $this->integer()->notNull(),
            'updated_at' => $this->integer()->notNull(),
        ], $tableOptions);
    }
    public function safeDown()
    {
        $this->dropTable(self::TBLNAME);
    }
}

创建数据表
yii migrate up

为保证数据实体的原子性,对admin设计应只涉及关键字段。对于个人资料等信息可另外设计profile表。

CREATE TABLE `admin` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `auth_key` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `password_reset_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `status` smallint(6) NOT NULL DEFAULT '10',
  `created_at` int(11) NOT NULL,
  `updated_at` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `password_reset_token` (`password_reset_token`)
) ENGINE=InnoDB AUTO_INCREMENT=500 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

关于采用InnoDB存储引擎,是否为表设计外键。考虑到日后大数据量操作给数据库带来瓶颈的风险。此时不采用数据库设计外键形式,而采用程序方式实现。

AUTO_INCRMENT=500 保留前499个账户为系统内置使用,思路来自Linux。

2 创建模型和CRUD操作

创建模型
创建CURD操作

3 管理员操作

3.1 新增管理员

控制器 /backend/controllers/AdminController.php

//加载表单模型
use backend\models\AdminForm;
//新增管理员
public function actionCreate()
{
    $model = new AdminForm();//新增表单模型处理新增操作
    if ($model->load(Yii::$app->request->post())) {
        if($model->create()){
//          return $this->render('view', ['id' => $model->id]);//此处报错 返回后获取不到id
            return $this->redirect(['index']);
        }
    } else {
        return $this->render('create', ['model' => $model]);
    }
}

管理员表单模型:/backend/models/AdminForm.php

<?php
namespace backend\models;
use Yii;
use yii\base\Model;

class AdminForm extends Model
{
    public $username;
    public $password;
    public $repassword;
    public $email;

    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'username' => Yii::t('app', 'Username'),
            'email' => Yii::t('app', 'Email'),
            'password' => Yii::t('app', 'Password'),
            'repassword' => Yii::t('app', 'Repassword'),
        ];
    }

    public function rules()
    {
        return [
            [['username', 'password', 'email'], 'required'],
            [['username', 'password', 'email'], 'filter', 'filter'=>'trim'],

            [['username','password'], 'string','min'=>6,'max'=>20],

            ['repassword', 'compare','compareAttribute'=>'password','message'=>'两次输出的密码不一致'],

            [['username'], 'unique','targetClass'=>'\backend\models\Admin','message'=>'账户已存在'],
            [['email'], 'unique','targetClass'=>'\backend\models\Admin','message'=>'邮箱已存在'],

            ['email', 'email'],
            ['email', 'string','max'=>128],
        ];
    }

    public function create()
    {
        if (!$this->validate()) {
            return null;
        }

        $model = new Admin();
        $model->username = $this->username;
        $model->email = $this->email;
        $model->setPassword($this->password);//管理员模型中设置密码
        $model->generateAuthKey();//管理员模型中设置认证字段

        return $model->save(false);
    }
}

管理员模型:/backend/models/Admin.php

<?php
namespace backend\models;
use Yii;

class Admin extends \yii\db\ActiveRecord
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    public static function tableName()
    {
        return '{{%admin}}';
    }
    public function rules()
    {
        return [
            [['username', 'email', 'password_hash', 'auth_key', 'created_at', 'updated_at'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['username', 'email', 'password_hash', 'password_reset_token'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['username'], 'unique'],
            [['email'], 'unique'],
            [['password_reset_token'], 'unique'],
        ];
    }
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'username' => Yii::t('app', 'Username'),
            'email' => Yii::t('app', 'Email'),
            'password_hash' => Yii::t('app', 'Password Hash'),
            'auth_key' => Yii::t('app', 'Auth Key'),
            'password_reset_token' => Yii::t('app', 'Password Reset Token'),
            'status' => Yii::t('app', 'Status'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
        ];
    }
    //前置操作
    public function beforeSave($data)
    {
        if(parent::beforeSave($data)){
            if($data){
                $this->created_at = $this->updated_at = time();
            }else{
                $this->updated_at = time();
            }
            return true;
        }else{
            return false;
        }
    }
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }
}


首页 /backend/views/index.php

首页
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
$this->title = Yii::t('app', 'Admins');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="admin-index">
    <?php Pjax::begin(); ?>
    <p>
        <?= Html::a(Yii::t('app', 'Create'), ['create'], ['class' => 'btn btn-success']) ?>
        <?= Html::a(Yii::t('app', 'Clean'), ['create'], ['class' => 'btn btn-danger']) ?>
    </p>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            ['attribute'=>'id','contentOptions'=>['width'=>'5%']],
            'username',
            'email:email',
            'status',
            ['attribute'=>'created_at', 'format'=>['date','php:Y-m-d H:i:s']],
            [
                'class' => 'yii\grid\ActionColumn',
                'template'=>'{view} {update} {delete} {reset} {privilege}',
                'buttons'=>[
                    'reset'=>function($url,$model,$key){
                        $options = [
                            'title'=>Yii::t('app', 'Reset'),
                            'aria-label'=>Yii::t('app', 'Reset'),
                            'data-pjax'=>'0'
                        ];
                        return Html::a('<span class="glyphicon glyphicon-lock"></span>', $url, $options);
                    },
                    'privilege'=>function($url,$model,$key){

                    }
                ]
            ],
        ],
    ]); ?>
    <?php Pjax::end(); ?>
</div>

新增页 /backend/views/create.php

新增页
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->title = Yii::t('app','Create');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Admins'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="admin-create">
    <div class="row">
        <div class="col-lg-5">
            <?php $form = ActiveForm::begin(['id' => 'form-create']); ?>
            <?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
            <?= $form->field($model, 'password')->passwordInput() ?>
            <?= $form->field($model, 'repassword')->passwordInput() ?>
            <?= $form->field($model, 'email') ?>
            <div class="form-group">
                <?= Html::submitButton(Yii::t('app','Create'), ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
            </div>
            <?php ActiveForm::end(); ?>
        </div>
    </div>
</div>

详情页 /backend/views/view.php

详情页
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
$this->title = $model->username;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Admins'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="admin-view">
    <p>
        <?= Html::a(Yii::t('app', 'Create'), ['create'], ['class' => 'btn btn-warning']) ?>
        <?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
        <?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
                'method' => 'post',
            ],
        ]) ?>
    </p>
    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'username',
            'email:email',
            'password_hash',
            'auth_key',
            'password_reset_token',
            'status',
            ['attribute'=>'created_at', 'format'=>['date','php:Y-m-d H:i:s']],
            ['attribute'=>'updated_at', 'format'=>['date','php:Y-m-d H:i:s']],
        ],
    ]) ?>
</div>

修改页 /backend/views/update.php

修改页
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="admin-form">
    <?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'status')->textInput() ?>
    <div class="form-group">
        <?= Html::submitButton(Yii::t('app', 'Update'), ['class' => 'btn btn-success']) ?>
    </div>
    <?php ActiveForm::end(); ?>
</div>

3.2 修改密码

首页添加按钮
/backend/views/admin/index.php

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        ['attribute'=>'id','contentOptions'=>['width'=>'5%']],
        'username',
        'email:email',
        'status',
        ['attribute'=>'created_at', 'format'=>['date','php:Y-m-d H:i:s']],
        // 重新设置操作按钮
        [
            'class' => 'yii\grid\ActionColumn',
            'template'=>'{view} {update} {delete} {reset} {privilege}',
            'buttons'=>[
                'reset'=>function($url,$model,$key){
                    $options = [
                        'title'=>Yii::t('app', 'Reset'),
                        'aria-label'=>Yii::t('app', 'Reset'),
                        'data-pjax'=>'0'
                    ];
                    return Html::a('<span class="glyphicon glyphicon-lock"></span>', $url, $options);
                },
                'privilege'=>function($url,$model,$key){

                }
            ]
        ],
    ],
]); ?>

控制器新增方法
/backend/controllers/AdminController.php

use backend\models\ResetForm;
//修改密码
public function actionReset($id)
{
    $model = new ResetForm();//创建独立表单模型
    if ($model->load(Yii::$app->request->post())) {
        if($model->reset($id)){
            return $this->redirect(['index']);//修改成功后返回首页
        }
    } else {
        return $this->render('reset', ['model' => $model]);
    }
}

新增表单模型
/backend/models/ResetForm.php

<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use backend\models\Admin;

class ResetForm extends Model
{
    public $password;
    public $repassword;

    public function attributeLabels()
    {
        return [
            'password' => Yii::t('app', 'Password'),
            'repassword' => Yii::t('app', 'Repassword'),
        ];
    }

    public function rules()
    {
        return [
            [['password', 'repassword'], 'required'],
            [['password', 'repassword'], 'filter', 'filter'=>'trim'],
            [['password','repassword'], 'string','min'=>6,'max'=>20],
            ['repassword', 'compare','compareAttribute'=>'password','message'=>'两次输出的密码不一致'],
        ];
    }

    public function reset($id)
    {
        if (!$this->validate()) {
            return null;
        }

        $model = Admin::findOne($id);
        $model->setPassword($this->password);

        return $model->save(false)?true:false;
    }

}

新增视图模板
/backend/views/admin/reset.php

重置密码页
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

$this->title = Yii::t('app','Reset');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Admins'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="admin-reset">
    <p>
        <?= Html::a(Yii::t('app', 'Back'), '/admin', ['class' => 'btn btn-info']) ?>
        <?= Html::a(Yii::t('app', 'Create'), ['create'], ['class' => 'btn btn-success']) ?>
    </p>
    <?php $form = ActiveForm::begin(['id' => 'form-reset']); ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <?= $form->field($model, 'repassword')->passwordInput() ?>
    <div class="form-group">
        <?= Html::submitButton(Yii::t('app','Reset'), ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
    </div>
    <?php ActiveForm::end(); ?>
</div>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容