php 获取yii2中的用户名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27858575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the name of the user in yii2
提问by Patricia Heimfarth
How can I get the name of the logged-in-user in yii2? I can get the user-id with
如何在 yii2 中获取登录用户的名称?我可以用
Yii::$app->user->id;
and I know that I could find the name in the database but I want a direct way. The name-column in the database has the name "username", but
我知道我可以在数据库中找到这个名字,但我想要一个直接的方法。数据库中的名称列具有名称“用户名”,但
Yii::$app->user->username;
doesn't work and
不起作用并且
Yii::$app->user->name;
doesn't work either.
也不起作用。
回答by Mr Peach
On login the user information will be stored in Yii::$app->user->identity
variable.
登录时,用户信息将存储在Yii::$app->user->identity
变量中。
For more information have a read through the User Authentication documentationin the official guide.
有关更多信息,请阅读官方指南中的用户身份验证文档。
回答by Wade
While the answer from @thepeach works, you can actually extend the User component and add your own functions, so that you can get them via Yii::$app->user->something
as you were initially trying to do.
虽然@thepeach 的答案有效,但您实际上可以扩展 User 组件并添加您自己的函数,以便您可以Yii::$app->user->something
像最初尝试那样通过它们来获取它们。
I like to extend things like this from the start, so I am ready to add custom functionality without having to refactor any code. It sucks to do things one way, then have to go back and fix 100 spots of code, because you changed it later.
我喜欢从一开始就扩展这样的东西,所以我准备添加自定义功能而无需重构任何代码。以一种方式做事很糟糕,然后不得不回去修复 100 个代码点,因为你后来改变了它。
First, define a user component class in your config:
首先,在您的配置中定义一个用户组件类:
'components' => [
'user' => [
'class' => 'app\components\User', // extend User component
],
],
Then create User.php
in your components
directory. If you haven't made this directory, create it in your app root.
然后User.php
在您的components
目录中创建。如果您尚未创建此目录,请在您的应用根目录中创建它。
User.php
用户名
<?php
namespace app\components;
use Yii;
/**
* Extended yii\web\User
*
* This allows us to do "Yii::$app->user->something" by adding getters
* like "public function getSomething()"
*
* So we can use variables and functions directly in `Yii::$app->user`
*/
class User extends \yii\web\User
{
public function getUsername()
{
return \Yii::$app->user->identity->username;
}
public function getName()
{
return \Yii::$app->user->identity->name;
}
}
Now you can access these through Yii::$app->user->something
.
现在您可以通过Yii::$app->user->something
.
For example, put this in one of your views and access the page in your browser:
例如,将其放在您的一个视图中并在浏览器中访问该页面:
<?= \Yii::$app->user->username ?>
I wrote a more detailed answer here, which covers this a bit more in depth.
我在这里写了一个更详细的答案,它更深入地介绍了这一点。
回答by rizesky
Easy, just use:
简单,只需使用:
<?= \Yii::$app->user->identity->username ?>