【问题标题】:ApiResource attribute gives Compile Error: Constant expression contains invalid operationsApiResource 属性给出编译错误:常量表达式包含无效操作
【发布时间】:2023-02-12 03:56:57
【问题描述】:

我正在尝试仅公开一些带有 API 平台的端点,如此处所述:https://api-platform.com/docs/v2.7/core/operations/

如果我只使用 ApiResource 属性,我会得到预期的结果(即默认的 CRUD 端点)。

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Metadata\ApiResource;
use App\Repository\MyclassRepository;

#[ORM\Entity(repositoryClass: MyclassRepository::class)]
#[ApiResource]
class Myclass
{
}

但是只显示某些操作的选项都不起作用。

这个:

#[ApiResource(operations=[
    new Get(),
    new GetCollection()
])]

... 只输出“规范中未定义任何操作!”在 /api/文档上。这也让 VSCode 对“operation=”感到愤怒:

Expression is not writable.intelephense(1024)
Undefined constant 'App\Entity\operations'.intelephense(1011)
Syntax error: unexpected token '='PHP(PHP2014)

这个:

#[ApiResource(
    operations: [
        new Get(),
        new GetCollection()
    ]
)]

... 产生错误“编译错误:常量表达式包含无效操作”。

  • 项目在 Docker php:8.0-fpm 上本地运行,“api-platform/core”:“^2.7”。
  • 存在适当的“使用”语句。
  • 我尝试了不同的方法和配置组合(例如 uriTemplate)。

我还尝试将 api-platform ^2.6 与:

#[ApiResource(
    collectionOperations: ['get'],
    itemOperations: ['get'],
)]

... 产生错误“未知命名参数 $collectionOperations”。

我错过了什么?

谢谢!!

【问题讨论】:

  • 没关系对不起!我终于偶然发现了一篇提到需要 PHP 8.1 而不是 8.0 的帖子 -_-
  • 我也遇到了这个问题,但是你的建议对我没有用。
  • @shaho1090 使用 PHP8.1,我帖子中的第三种方法有效,即 #[ApiResource( operations: [ new Get(), new Post() ] )]
  • 你是对的,我的旧 Phpstorm 基于高达 8.0 的 PHP 语言级别工作,并继续提醒我那行代码,我更新了它并将 PHP 版本设置为 8.2,这是一个较新的版本,这些警报消失了。谢谢你!

标签: api-platform.com


【解决方案1】:

API 平台需要 PHP 8.1,而不是 8.0。升级后,这有效:

#[ApiResource(
    operations: [
        new Get(),
        new GetCollection()
    ]
)]

【讨论】:

    猜你喜欢
    • 2017-05-16
    • 2017-03-03
    • 2018-12-02
    • 2021-03-07
    • 2017-04-11
    相关资源
    最近更新 更多