Yii2后台用户与前台用户分离

Yii2实践教程 2019年9月22日 3.14K
前后台用户的分离,相信不用我多介绍大家应该也能理解为啥要分离啦。我们的Yii2安装完后通过命令 /path/to/php-bin/php /path/to/yii-application/yii migrate 创建数据库user和migration,其中user表就是高级模版注册和登录的用户表,但是是前后台通用的,因此我们将要把前后台的用户做一个完全的分离,方便对前后台用户的管理。
首先创建后台用户表
执行命令:yii migrate/create ff_admin_user 这样会在 /console/migrations/目录下生成一个新文件(第十篇会介绍migrate)打开生产的文件,修改想要的迁移文件。
//创建数据库
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}

$this->createTable($this->prefix.'_admin_user', [
'id' => $this->primaryKey(),
'username' => $this->string()->notNull()->unique(),
'auth_key' => $this->string(32)->notNull(),
'password_hash' => $this->string()->notNull(),
'password_reset_token' => $this->string()->unique(),
'email' => $this->string()->notNull()->unique(),
'status' => $this->smallInteger()->notNull()->defaultValue(10),
'create_at' => $this->integer()->notNull(),
'update_at' => $this->integer()->notNull()
], $tableOptions);
}
//删除数据库
public function down()
{
$this->dropTable($this->prefix.'_admin_user');
}
运行命令:yii migrate 会生成对于的数据库。

[wppay]

再次调整配置和controller文件
打开backend/config/main.php文件,修改对于user的部分如下:
'user' => [
'identityClass' =>'backend\models\AdminUser',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
之后复制 /common/models/User.php和LoginForm.php文件到 /backend/models/下,将User.php修改为AdminUser.php,打开文件修改namespaces为backend\models;类名为AdminUser,方法tabelName()为对应的数据库。
修改后台 backend/controllers/SiteController.php 的 use 部分
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
//use common\models\LoginForm; //修改前
use backend\models\LoginForm; //修改后,后台可以使用自己的LoginForm

修改backend/models/LoginForm.php文件的use部分
//namespace common\models; //修改前
namespace backend\models; //修改后
至此调整完毕,可以在ff_admin_user表中添加一条数据,然后在将后台的注册功能关闭,就可以调整后台啦。
注:ff_admin_user的数据可以将user表中的一条复制过去。

[/wppay]

未经允许不得转载:飞飞学院 » Yii2后台用户与前台用户分离

文章评论

您需要之后才可以评论
18点赞 0评论 收藏 QQ分享 微博分享