And*_*sen 4 model view yii2 yii2-user
我想扩展自己的用户模型,使用一个名为getFirstname的函数.该函数应返回数据库中的自定义字段.
但是当我扩展用户模型时.它说"调用未知方法:yii\web\User :: getFirstname()"
我在app\models\user中的用户模型.我删除了文件中与此问题无关的方法.
<?php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
/**
* User model
*
*/
class User extends ActiveRecord implements IdentityInterface
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [];
}
/**
* Finds user by email
*
* @param string $email
* @return static|null
*/
public static function findByEmail($username)
{
return static::findOne(['user_email' => $username]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
public function getFirstname()
{
return $this->user_firstname;
}
}
Run Code Online (Sandbox Code Playgroud)
我的配置文件:
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'thepaXucufrE2pefRethaxetrusacRu3',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'loginUrl' => ['login/sign-in'],
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
];
Run Code Online (Sandbox Code Playgroud)
在我的视图文件中:
<?= Yii::$app->user->getFirstname() ?>
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
试试这个:
<?= Yii::$app->user->identity->getFirstname() ?>
<!-- or -->
<?= Yii::$app->user->identity->firstname ?>
Run Code Online (Sandbox Code Playgroud)
有了Yii::$app->user你刚才得到的用户组件.该用户组件类注释告诉你:
用户是管理用户身份验证状态的"用户"应用程序组件的类.
因此,它不是您使用的实际用户Yii::$app->user,而是管理组件.使用identity或者getIdentity()使用此类,您将获得实现IdentityInterface的用户对象.当你看一下:你的User类实现了这个接口.在您的配置中,您告诉用户组件它应该完全使用您的User类.