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>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容