Symfony 错误:属性“Symfony\Component\Routing\Annotation\Route”无法定位函数(允许的目标:类、方法)

Tho*_*uer 2 php symfony

从 Symfony 6.1 升级到 6.2 后,我收到此错误:

属性“Symfony\Component\Routing\Annotation\Route”无法定位函数(允许的目标:类、方法)

...在此控制器上:

final class HomepageController extends AbstractController
{
    #[Route(path: '/', name: 'homepage')]
    public function __invoke(): Response
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*uer 5

简答

执行以下操作之一即可修复该问题:

  • 将 PHP 更新至 >= 8.1.10
  • Route属性从__invoke()上移至class

长答案

Symfony 的Route属性允许在类和方法上使用,请参阅Route

#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD)]
Run Code Online (Sandbox Code Playgroud)

在 Symfony 6.2 中,读取属性的方式已更改: https: //github.com/symfony/symfony/pull/46001

不幸的是,PHP 8.1.6 中引入了一个错误,因此__invoke()不再涵盖该魔术方法\Attribute::TARGET_METHOD

这已在 PHP 8.1.10 中修复:https ://github.com/php/php-src/pull/9173