Yii2与layuiadmin整合1

1.下载对应Yii2框架,这里以官方的基本应用程序模板

composer create-project --prefer-dist yiisoft/yii2-app-basic yii2web

2.配置站点

3.开启伪静态在文件 中 添加开启 /config/web.php

$config = [
    // 
    'components' => [
        // 
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        // 

4.建立数据库并配置数据库连接,修改文件  /config/db.php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2web',
    'username' => 'root',
    'password' => 'root',
    'charset' => 'utf8',
];    

以下建立文件时,如果目录不存在,则手动直接建立目录即可,
主机为 http://yii2web.com

5.通过命令方式分别建立以下模块功能 http://yii2web.com/gii/module
users, orders, products, purchases, system

// Module Class
app\modules\users\Module

// Module ID
users

// Module Class
app\modules\orders\Module

// Module ID
orders

// Module Class
app\modules\products\Module

// Module ID
products

// Module Class
app\modules\purchases\Module

// Module ID
purchases

// Module Class
app\modules\system\Module

// Module ID
system

6.在配置文件添加以上模块,修改文件 /config/web.php

//
$config = [
    'id' => 'basic',
    //
    // 添加模块
    'modules' => [
        'users' => [
            'class' => 'app\modules\users\Module',
        ],
        'orders' => [
            'class' => 'app\modules\orders\Module',
        ],
        'products' => [
            'class' => 'app\modules\products\Module',
        ],
        'purchases' => [
            'class' => 'app\modules\purchases\Module',
        ],
        'system' => [
            'class' => 'app\modules\system\Module',
        ],
    ],
// 

以上可以直接访问  http://yii2web.com/users/default/index

7.加载layuiadmin,以 /layuiAdmin/admin/std/dist/下的文件为例
复制整个目录layuiadmin及目录下的文件 到 /web/assets/

8.建立前端配置文件 /assets/LayuiAsset.php

<?php

namespace app\assets;

use yii\web\AssetBundle;

class LayuiAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';

    public $css = [
        'assets/layuiadmin/layui/css/layui.css',
        'assets/layuiadmin/style/admin.css',
        'assets/layuiadmin/style/login.css'
    ];

    public $js = [
        'assets/layuiadmin/layui/layui.js',
    ];
    
    public $jsOptions = ['position' => View::POS_HEAD,];

    public $depends = [];

    //定义按需加载JS方法,注意加载顺序在最后
    public static function addScript($view, $jsfile) {
        $view->registerJsFile($jsfile, [AppAsset::className(), 'depends' => 'app\assets\LayuiAsset']);
    }

    //定义按需加载css方法,注意加载顺序在最后
    public static function addCss($view, $cssfile) {
        $view->registerCssFile($cssfile, [AppAsset::className(), 'depends' => 'app\assets\LayuiAsset']);
    }
}

9.开发登陆页面
这里以自带的模板为基本修改
修改 文件 /controllers/SiteController.php,现在先开发测试,后面再一步步完善

class SiteController extends Controller
{
//
    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        $this->layout='empty';
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) ) {
            var_dump(11);
            print_r(Yii::$app->request->post());
            exit();
        }

        $model->password = '';

        return $this->render('login', [
            'model' => $model,
        ]);
    

10.新建上面的模板文件  /views/layouts/empty.php

<?php

/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use app\assets\LayuiAsset;

LayuiAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

11.修改模板  /views/site/login.php

<?php
use yii\bootstrap4\ActiveForm;
?>
<div class="layadmin-user-login layadmin-user-display-show" id="LAY-user-login" style="display: none;">
    <div class="layadmin-user-login-main">
        <div class="layadmin-user-login-box layadmin-user-login-header">
            <h2>layuiAdmin</h2>
        </div>
        <?php $form = ActiveForm::begin(); ?>
        <div class="layadmin-user-login-box layadmin-user-login-body layui-form">

            <div class="layui-form-item">
                <?= $form->field($model, 'username')
                    ->textInput(['type' => 'text', 'lay-verify' => 'required','class' => 'layui-input','placeholder' => '用户名','id' => 'LAY-user-login-username'])
                    ->label('用户名');
                ?>
            </div>

            <div class="layui-form-item">
                <?= $form->field($model, 'password')
                    ->textInput(['type' => 'password','id' => 'LAY-user-login-password', 'lay-verify' => 'required','class' => 'layui-input','placeholder' => '密码'])
                    ->label('密码');
                ?>
                <?= $form->field($model, 'rememberMe')->textInput(['type'=>'hidden','value' => 1])->label('记住密码');?>
            </div>

            <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="LAY-user-login-submit">登 入</button>
            </div>

        </div>
        <?php ActiveForm::end();?>
    </div>
</div>

此时可以访问 http://yii2.com/site/login 并模似登陆提交了

12.为了方便测试用户认证,先处理用户添加与登陆认证
建立用户表

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `auth_key` varchar(64) NOT NULL,
  `password_hash` varchar(255) NOT NULL,
  `password_reset_token` varchar(255) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `phone` varchar(30) DEFAULT NULL,
  `status` tinyint(1) DEFAULT '1',
  `created_at` int(11) NOT NULL,
  `updated_at` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

13.建立对应的用户功能,执行
http://yii2web.com/gii/controller

Controller Class: 
app\modules\users\controllers\UserController

其它保持默认
直接生成

14.建立添加用户的模型
/modules/users/models/SignupForm.php
添加以下的内容

<?php

namespace app\modules\users\models;

use app\models\User;
use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 *
 * @property-read User|null $user
 *
 */
class SignupForm extends Model
{
    public $username;
    public $password;


    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            ['username', 'filter', 'filter' => 'trim'],
            ['username','unique','targetClass' => '\app\models\User', 'message' => 'This username has already been taken.','on'=>['create']],
            ['username', 'string', 'min' => 5, 'max' => 255],

            // password is validated by validatePassword()
            [['password'], 'required','on'=>['create']],
            ['password', 'string', 'min' => 6],
        ];
    }

    /** 注册用户
     * @return User|null
     */
    public function signup()
    {
        if($this->validate()) {
            $user = new User();
            $user->username = $this->username;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            $user->save();
            if($user->save()) {
                return $user;
            }
        }
        return null;
    }

    public function findOne($id)
    {
        $user = User::findOne($id);
        $this->username = $user->username;
        return $this;
    }

    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'password' => '密码',
        ];
    }


}

15.修改 /models/User.php 内容修改如下

<?php
namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $password write-only password
 */
class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 1;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username','required'],
            [['created_at','updated_at'],'integer'],
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

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

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

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

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        return $timestamp + $expire >= time();
    }

    /**
     * @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 Yii::$app->security->validatePassword($password, $this->password_hash);
    }

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

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

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

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

16. 在 /modules/users/controllers/UserController.php
修改为如下

<?php

namespace app\modules\users\controllers;

use Yii;
use yii\web\Controller;
use app\modules\users\models\SignupForm;

class UserController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 添加用户
     */
    public function actionCreate() {
        $this->layout='@app/views/layouts/empty';
        $model = new SignupForm();
        $model->setScenario('create');
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                exit('success');
            }
        }
        return $this->render('create',[
            'model' => $model
        ]);

    }

}

 

posted @ 2022-02-08 09:22  好记性还真不如烂笔头  阅读(388)  评论(0编辑  收藏  举报