安装Yii2-User
我们这里的Yii2-User
安装步骤参照Yii2-User
的官方安装文档。我们直接使用composer来进行安装:
composer require "dektrium/yii2-user:0.9.*@dev"
稍微等待一下,安装完毕之后就可以进行对应的配置了,我们需要配置的文件是config/web.php
,找到components
,然后在与它同级的位置增加一个modules
:
'components' => [
],
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
'confirmWithin' => 21600,
'cost' => 12,
'admins' => ['admin']
],
],
这里还需要将components
下面的user
部分注释掉,不然就会一直登录不了:
/* 'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],*/
还有最后一步就是执行Yii2-User的migration
了,在helloYii/
目录下执行:
php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations
然后你会看到:
果断yes
Bang,到这里Yii2-User安装和配置已经完成了。
配置SwiftMailer
安装完Yii2-User之后我们先不急着去想怎么实现登录和注册(其实很是比较简单的),我们之前说过的目标是实现用户在注册时候发送验证邮件的,这里我们先来配置一下我们的邮箱服务,因为Yii2-User可以直接使用邮箱来进行注册验证和密码找回等功能。在config/web.php
找到mailer
这个部分:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => true,
],
修改成我们下面的这个样子:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@app/mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.163.com',
'username' => $params['adminEmail'],
'password' => 'your-password',
'port' => '25',
'encryption' => 'tls',
],
],
在config/params.php
改成自己的邮箱
<?php
return [
'adminEmail' => "13132693017@163.com",
];
开始使用Yii2-User
邮箱配置好了之后,我们就可以开始使用Yii2-User了,首先我们来修改一下我们的导航栏,因为我们想实现的就是我们常常看到的在导航栏的右侧的注册和登录按钮。在/views/layouts/main.php
找到:
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => [
['label' => 'Home', 'url' => ['/site/index']],
[
'label' => 'Status',
'items' => [
['label' => 'View', 'url' => ['/status/index']],
['label' => 'Create', 'url' => ['/status/create']],
],
],
['label' => 'About', 'url' => ['/site/about']],
['label' => 'Contact', 'url' => ['/site/contact']],
Yii::$app->user->isGuest ?
['label' => 'Login', 'url' => ['/site/login']] :
['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']],
],
]);
上面的启示就是我们在上一篇文章修改过后的导航栏的代码,然后用下面的代码进行替换:
$navItems=[
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']],
['label' => 'Contact', 'url' => ['/site/contact']]
];
if (Yii::$app->user->isGuest) {
array_push($navItems,['label' => 'Sign In', 'url' => ['/user/login']],['label' => 'Sign Up', 'url' => ['/user/register']]);
} else {
array_push($navItems,['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']]
);
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $navItems,
]);