API 平台自定义控制器 return 错误 500 "Controller [name] does neither exist as service nor as class"

API Platform custom controller return error 500 "Controller [name] does neither exist as service nor as class"

我想从我的 React 前端注册一个用户到我的 symfony/apiplatform API。 我从 API 平台 Creating Custom Operations and Controllers

的文档中得到灵感

我为注册创建了一个特定的路线/api/register

我的用户实体:


namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\SerializedName;
use App\Controller\RegisterController;

/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @ApiResource(
 *     normalizationContext={"groups"={"user:read"}},
 *     denormalizationContext={"groups"={"user:write"}},
 *     collectionOperations={
 *          "get",
 *          "post",
 *          "register" = {
 *              "method" = "POST",
 *              "path" = "/register",
 *              "controller" = "RegisterController::class",
 *          }
 *      }
 * )
 */
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @Groups("user:read")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     * @Groups({"user:read", "user:write"})
     */
    private $email;

    /**
     * @ORM\Column(type="json")
     * @Groups("user:read")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @Groups("user:write")
     * @SerializedName("password")
     */
    private $plainPassword;

    /**
     * @ORM\Column(type="string", length=128, nullable=true)
     * @Groups({"user:read", "user:write"})
     */
    private $pseudo;

    /**
     * @ORM\Column(type="string", length=32, nullable=true)
     * @Groups({"user:read", "user:write"})
     */
    private $name;

    /**
     * @ORM\Column(type="date", nullable=true)
     */
    private $birthday;

    /**
     * @ORM\Column(type="string", length=32, nullable=true)
     */
    private $surname;

I don't show the getters and setters for more visibility.

我的具体控制器:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Entity\User;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpKernel\Attribute\AsController;

#[AsController]
class RegisterController extends AbstractController
{
    private $managerRegistry;
    public function __construct(ManagerRegistry $managerRegistry)
    {
        $this->managerRegistry = $managerRegistry;
    }

    public function __invoke(User $data): User
    {

        var_dump("I'm in RegisterController");
        return $data;
    }
}

As it's extended from AbstractController, the controller is autowired from symfony kernel according to Symfony 5.3 - How to Define Controllers as Services

这是我的 services.yml :

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration
parameters:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'
            - '../src/Tests/'

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

如您所见,我不排除“控制器”

这是我的php bin/console debug:router

 ------------------------------- -------- -------- ------ -------------------------------------
  Name                            Method   Scheme   Host   Path
 ------------------------------- -------- -------- ------ -------------------------------------
  _wdt                            ANY      ANY      ANY    /_wdt/{token}
  _profiler_home                  ANY      ANY      ANY    /_profiler/
  _profiler_search                ANY      ANY      ANY    /_profiler/search
  _profiler_search_bar            ANY      ANY      ANY    /_profiler/search_bar
  _profiler_phpinfo               ANY      ANY      ANY    /_profiler/phpinfo
  _profiler_search_results        ANY      ANY      ANY    /_profiler/{token}/search/results
  _profiler_open_file             ANY      ANY      ANY    /_profiler/open
  _profiler                       ANY      ANY      ANY    /_profiler/{token}
  _profiler_router                ANY      ANY      ANY    /_profiler/{token}/router
  _profiler_exception             ANY      ANY      ANY    /_profiler/{token}/exception
  _profiler_exception_css         ANY      ANY      ANY    /_profiler/{token}/exception.css
  home                            ANY      ANY      ANY    /{reactRouting}
  api_entrypoint                  ANY      ANY      ANY    /api/{index}.{_format}
  api_doc                         ANY      ANY      ANY    /api/docs.{_format}
  api_jsonld_context              ANY      ANY      ANY    /api/contexts/{shortName}.{_format}
  api_users_get_collection        GET      ANY      ANY    /api/users.{_format}
  api_users_post_collection       POST     ANY      ANY    /api/users.{_format}
  api_users_register_collection   POST     ANY      ANY    /api/register
  api_users_get_item              GET      ANY      ANY    /api/users/{id}.{_format}
  api_users_delete_item           DELETE   ANY      ANY    /api/users/{id}.{_format}
  api_users_put_item              PUT      ANY      ANY    /api/users/{id}.{_format}
  api_users_patch_item            PATCH    ANY      ANY    /api/users/{id}.{_format}
  _preview_error                  ANY      ANY      ANY    /_error/{code}.{_format}
  authentication_token            POST     ANY      ANY    /api/login
 ------------------------------- -------- -------- ------ -------------------------------------

您可以注意到路线 /api/register 存在

它应该正常工作,因为它是 Symfony/API 平台的默认行为。 当我使用邮递员时,出现此错误:

我试图在互联网上找到一些解决方案并尝试清除生产和开发中的缓存,但我仍然遇到问题。

请问如何解决这个错误?

正如@Cerad 在评论中所说,我需要去掉双引号。

我替换的内容:

"controller" = "RegisterController::class"

"controller" = RegisterController::class