Symfony 和 Doctrine ParamConverter 在 AbstractController 中使用

Symfony and Doctrine ParamConverter used out of an AbstractController

我正在尝试编写一个不扩展 Symfony 的“classic”AbstractController 的控制器,我想使用内部的 ParamConverter 作为注释。 控制器代码如下:

<?php

declare(strict_types=1);

namespace App\Controller\Chat;

use App\Entity\Message;
use App\Entity\User;
use App\Service\DeleteMessage;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use function assert;

final class MessageMarkAsDeletedController
{
    private DeleteMessage $deleteMessage;

    private Security $security;

    public function __construct(DeleteMessage $deleteMessage, Security $security)
    {
        $this->deleteMessage = $deleteMessage;
        $this->security      = $security;
    }

    /**
     * @Route("/message/{messageId}/remove", name="chat_message_mark_as_deleted", methods={"POST"})
     * @ParamConverter("message", class="App\Entity\Message", options={"id" = "messageId"})
     */
    public function markAsDeleted(Message $message) : JsonResponse
    {
        $user = $this->security->getUser();
        assert($user instanceof User);

        if (! ($message->getFromUser() === $user->getId())) {
            return new JsonResponse(['error' => 'You don\'t have permissions to delete this message'], 404);
        }

        if ($message->isDeleted()) {
            return new JsonResponse(['error' => 'The specified message has already been deleted'], 400);
        }

        $this->deleteMessage->delete($message);

        return new JsonResponse(['payload' => ['success' => true]], 204);
    }
}

当我将代码推送到 gitlab 时,管道启动并出现错误:

Symfony \ Component \ Config \ Exception \ LoaderLoadException: [Semantical Error] The annotation "@Sensio \ Bundle \ FrameworkExtraBundle \ Request \ ParamConverter" in method App \ Controller \ Chat \ MessageMarkAsDeletedController :: markAsDeleted () does not exist, or could not be auto-loaded in /app/config/routes/../../src/Controller/Chat (which is being imported from "/app/config/routes/api.yaml"). Make sure annotations are installed and enabled.

你知道问题出在哪里吗?我在理解如何使用 ParamConverter 和 symfony 文档时遇到一些问题,所有示例都是在扩展 AbstractController 的控制器 class 中完成的,我认为我的理解问题来自那里

如果它在本地运行但不适用于您的管道(我猜它在生产环境中运行),则可能意味着 ParamConverter 仅在开发环境中可用。

请确保 sensio/framework-extra-bundle 在您的 composer.json 中注册为 require-dev 依赖项,但作为常规 require依赖。

当然,您可以尝试重新安装捆绑包:

composer remove sensio/framework-extra-bundle && composer require sensio/framework-extra-bundle

而不是

use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter;

(恕我直言不存在)你应该使用

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html

所建议