gpt4 book ai didi

php - 获取当前登录用户 - symfony 4

转载 作者:行者123 更新时间:2023-12-02 01:59:12 25 4
gpt4 key购买 nike

public function agencyHome(EntityManagerInterface $em)
{
$repository = $em->getRepository(Ships::class);
// $ships = $repository->findByOwner($own);
$ships = $repository->findAll();
return $this->render('agency/index.html.twig', [
'ships' => $ships,
]);
}

在上面的代码中,我需要将当前登录的用户传递到存储库,这样我就可以找到所有相关的“船舶”我尝试使用 $u = $this->getUser()->getId();没有成功:(

提前谢谢您:)

最佳答案

在 Symfony 4 Controller 中,如果用户已获得授权,您应该能够在 Controller 内使用 $this->getUser() 访问用户。如果没有登录用户,则应返回null

public function agencyHome(EntityManagerInterface $em)
{
$this->denyAccessUnlessGranted('ROLE_USER');
$user = $this->getUser();
}

或者,您还应该能够将 UserInterface 类注入(inject)到方法参数中,通过该类您可以获得有关当前登录用户的信息。

public function agencyHome(EntityManagerInterface $em, UserInterface $user)
{
...
}

我已经在 Symfony 4 应用程序上测试了这些,但我不记得是否需要在配置中执行其他操作,因此如果您对它们有任何问题,请告诉我。

引用自https://symfony.com/doc/current/security.html

关于php - 获取当前登录用户 - symfony 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51806390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com