Nette getUser在组件中

Muh*_*aha 2 php components username nette

我不得不问如何将已登录用户的名称输入Nette组件(SomethingControl.php).显然我不能这样做:

    $identity = $this->getUser()->getIdentity();
    if ($identity) $this->template->username = $identity->getData()['username'];
Run Code Online (Sandbox Code Playgroud)

所以我试过这个:

$this->template->username = $this->user
Run Code Online (Sandbox Code Playgroud)

但这也不起作用.

mrt*_*lml 5

你不能得到这样的用户,因为UI\Control它不是UI\Presenter的后代.但是Nette\Security\User服务是在DIC注册的,所以你可以这样得到它:

class SomethingControl extends \Nette\Application\UI\Control
{

    /**
     * @var \Nette\Security\User
     */
    private $user;

    public function __construct(\Nette\Security\User $user)
    {
        parent::__construct();
        $this->user = $user;
    }

    public function render()
    {
        bdump($this->user); // getIdentity and username
    }

}
Run Code Online (Sandbox Code Playgroud)

只需确保您使用的是组件工厂 - 意味着不要使用new运算符在演示者中创建组件.

  • 使用依赖注入是最好的方法。 (2认同)