controller cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?
Asked Answered
P

2

5

I created this controller

<?php

namespace App\Controller;

use App\Interface\GetDataServiceInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

#[Route('/api')]
class ApiController
{
    private GetDataServiceInterface $getDataService;

    public function __construct(GetDataServiceInterface $getDataService)
    {
        $this->getDataService = $getDataService;
    }

    #[Route('/products', name: 'products', methods: ['GET'])]
    public function products(): Response
    {
        
        return new Response(
            $this->getDataService->getData()
        );
    }
}

then I setted the autowiring for GetDataServiceInterface on services.yml

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'
    
    App\Service\GetJsonDataService: ~
    App\Interface\GetDataServiceInterface: '@App\Services\GetJsonDataService'

this is the interface

<?php

namespace App\Interface;

interface GetDataServiceInterface
{
    public function getData():string;
}

and the service

<?php

namespace App\Service;

use App\Interface\GetDataServiceInterface;

class GetJsonDataService implements GetDataServiceInterface
{
    public function getData():string
    {
        return getcwd();
    }
}

but now I get this error when I try to make a request

The controller for URI "/api/products" is not callable: Controller "App\Controller\ApiController" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?

I'm not sure what else I have to set

Pitchman answered 19/10, 2022 at 18:19 Comment(0)
L
16

Your controller does not extend the AbstractController so you have to manually tag it as controller.service_arguments in services.yaml

https://symfony.com/doc/current/controller/service.html

Liver answered 19/10, 2022 at 21:50 Comment(0)
S
0

In addition to bechir's answer, also make sure you are using namespace App\Controller; at the top of the class document. It'll throw this error without it.

Skullcap answered 3/7, 2023 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.