Yii2,登录后但不更改为注销。以及如何在登录后从数据库中获取 Id

Yii2, After Login But not change to Logout. and How to get Id from database after login

我已经尝试了 Tutorial From Youtobe 的教程。

登录成功。但登录标签仍然是登录标签,没有更改为注销和用户名。

我还没看懂

1. Yii::t('app','Nama Admin') in Admin class which implement IdentityInterface ?

2. Where is Yii::$app->user->isGuest in main.php ? or how to read this ?

下面是代码。

Admin 是实现 IdentityInterface 的用户 Class。

 public static function tableName()
    {
        return 'admin';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['namaAdmin', 'username', 'password', 'authKey'], 'required'],
            [['namaAdmin', 'password'], 'string', 'max' => 20],
            [['username'], 'string', 'max' => 25],
            [['authKey'], 'string', 'max' => 50],
        ];
    }

public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'namaAdmin' => Yii::t('app','Nama Admin'),
            'username' => Yii::t('app','Username'),
            'password' => Yii::t('app','Password'),
            'authKey' => Yii::t('app','Auth Key'),
        ];
    }

部分方法与视频相同

some function on model > Login.php

public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = Admin::findByUsername($this->username);
        }

        return $this->_user;
    }

Login & Logout Action on SiteControler

public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }


    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

label Login/logout on main.php

Yii::$app->user->isGuest ? (
                ['label' => 'Login', 'url' => ['/site/login']]
            ) : (
                '<li>'
                . Html::beginForm(['/site/logout'], 'post', ['class' => 'navbar-form'])
                . Html::submitButton(
                    'Logout (' . Yii::$app->user->identity->username . ')',
                    ['class' => 'btn btn-link']
                )
                . Html::endForm()
                . '</li>'
            )

config/web.php 中将 user 数组更改为以下内容:

'user' => [
  'identityClass' => 'app\models\Admin',
  'enableAutoLogin' => true,
]