简体   繁体   中英

Yii2: call custom method in class User from view

I would like to extend my own user model, with a function called getFirstname. The function should return a custom field in the database.

But when I extend the user model. It says "Calling unknown method: yii\\web\\User::getFirstname()"

My user model in app\\models\\user. I have removed methods in the file, that are not relevant for this problem.

<?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;
    }  
}

My config file:

$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'),
    ],
];

And in my view file:

<?= Yii::$app->user->getFirstname() ?>

What am I doing wrong here?

Try this:

<?= Yii::$app->user->identity->getFirstname() ?>

<!-- or -->

<?= Yii::$app->user->identity->firstname ?>

With Yii::$app->user you just get the user component . The User component class comment tells you:

User is the class for the "user" application component that manages the user authentication status.

So it is not the actual user that you get with Yii::$app->user , it is the managing component. With identity or getIdentity() of this class you get the user object that is implementing the IdentityInterface. And when you have a look: your User class implements this interface. And in your configuration you tell the user component that it should use exactly your User class.

The User class with the getFirstname method is in the \\app\\models namespace, but the one being called in your view is in the yii\\web namespace. You should change the code to use \\app\\models\\User .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM