Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom operation in API Platform doesn't autowire the entity

I'am adding custom POST operation as describe https://api-platform.com/docs/core/operations/#recommended-method

But i each time face an error saying my action doesn't find my entity as service:

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

Here is my action:

class UserCreateAction extends BaseAction
{
    private $userService;

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

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

Normally, the action should automatically recognise the $user entity

like image 858
Duhamel Avatar asked Oct 27 '25 08:10

Duhamel


2 Answers

EDIT (2022/29/11): Please refer to the comment of @Cerad below for the fix.

I realised it's because of my services.yml.
Actually, among resources which should be available to be used as service, the Entity/ folder was excluded:

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

So I changed it, I removed the "Entity", and it works fine now:

App\:
    resource: '../src/*'
    exclude: '../src/{DependencyInjection,Migrations,Tests,Kernel.php}'
like image 196
Duhamel Avatar answered Oct 29 '25 21:10

Duhamel


This is very strange case - you are trying to create user that already exists (api platform loads it from your request uri) This is illegal operation. Remove User $user argument from __invoke and inject 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);
    }
}

To understand how it works read about ParamConverter in symfony. When you trying to inject entity into you controller __invoke method - api platform tries to find entity by {id} in database. This is applicable for item operations.

 *     itemOperations={
 *         "custom": {
 *             "method": "GET",
 *             "path": "/users/{id}",
like image 1
alvery Avatar answered Oct 29 '25 21:10

alvery