API 平台中的自定义操作不会自动装配实体

Custom operation in API Platform doesn't autowire the entity

我正在按照描述添加自定义 POST 操作 https://api-platform.com/docs/core/operations/#recommended-method

但我每次都遇到一个错误,说我的操作没有找到我的实体作为服务:

"hydra:description": "Cannot autowire argument $user of \"App\Controller\SDK\User\UserCreateAction()\": it references class \"App\Entity\SDK\User\" but no such service exists."

这是我的操作:

class UserCreateAction extends BaseAction
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function __invoke(User $user)
    {
        return $this->userService->create($user);
    }
}

通常情况下,操作应该会自动识别 $user 实体

我意识到这是因为我的 services.yml
实际上,在应该可以用作服务的资源中,Entity/ 文件夹被排除在外:

App\:
    resource: '../src/*'
    exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

所以我改变了它,我删除了 "Entity",现在它工作正常: (编辑:请参考下面@Cerad 的评论以进行修复。)

App\:
    resource: '../src/*'
    exclude: '../src/{DependencyInjection,Migrations,Tests,Kernel.php}'

这是非常奇怪的情况 - 您正在尝试创建已经存在的用户(api 平台从您的请求 uri 加载它)这是非法操作。从 __invoke 中删除 User $user 参数并注入 Request:

class UserCreateAction extends BaseAction
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function __invoke(Request $request)
    {
        $userFields = \json_decode($request->getContent(), true);

        return $this->userService->create($userFields);
    }
}

要了解它是如何工作的,请阅读 symfony 中的 ParamConverter。当您尝试将实体注入控制器 __invoke 方法时 - api 平台尝试通过数据库中的 {id} 查找实体。这适用于项目操作。

 *     itemOperations={
 *         "custom": {
 *             "method": "GET",
 *             "path": "/users/{id}",

就像任何常规控制器一样,确保可以注入服务:

# symfony/config/services.yaml
    App\ApiPlatform\Controller\CreateBookPublication:
        tags: ['controller.service_arguments']

<?php
// App\ApiPlatform\Controller\CreateBookPublication.php

namespace App\ApiPlatform\Controller;

use App\Entity\Book;

class CreateBookPublication
{
    private $bookPublishingHandler;

    public function __construct(BookPublishingHandler $bookPublishingHandler)
    {
        $this->bookPublishingHandler = $bookPublishingHandler;
    }

    public function __invoke(Book $data): Book
    {
        $this->bookPublishingHandler->handle($data);

        return $data;
    }
}