Den*_*off 10 php symfony php-attributes
<?php
declare(strict_types=1);
namespace App\Controller\User;
use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
#[Route('/users', name: 'user.')]
class UserController extends AbstractController
{
#[Route(name: 'list')]
public function list(#[CurrentUser] ?User $user, Request $request): Response {
dd($user->getFirstName());
}
Run Code Online (Sandbox Code Playgroud)
说的
Call to a member function getFirstName() on null
但我已获得授权。在 Symfony Profiler 中,它显示我已登录。
环境:PHP 8.0.11 Symfony 5.3.9
Den*_*off 10
有关解决方案的正确详细信息由/sf/users/80123921/ Symfony #[CurrentUser] 属性返回 null提供
该问题是由启用ParamConvertor
( sensio/framework-extra-bundle
) 引起的。由于缺乏如何从数据库获取实体的定义,它无法解析 User,因此它将 $user 变量设置为null
nullable #[CurrentUser] ?User $user
。如果你想同时保留参数转换器和#[CurrentUser]属性的功能,你应该禁用自动转换#
config/packages/sensio_framework_extra.yaml
sensio_framework_extra:
request:
converters: true
auto_convert: false
Run Code Online (Sandbox Code Playgroud)
并每次手动定义路由参数。资料来源: https://symfony.com/bundles/SensioFrameworkExtraBundle/current/annotations/converters.html https://symfony.com/blog/new-in-symfony-5-2-controller-argument-attributes https:// symfony.com/doc/current/controller/argument_value_resolver.html
避免此类问题的解决方案:以 200% 浏览器比例阅读文档。
归档时间: |
|
查看次数: |
3028 次 |
最近记录: |