无法从容器中获取控制器,因为它是私有的。您是否忘记用“controller.service_arguments”标记服务?

a_d*_*v85 5 php symfony symfony6

我创建了这个控制器

<?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()
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

GetDataServiceInterface然后我在 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'
Run Code Online (Sandbox Code Playgroud)

这是界面

<?php

namespace App\Interface;

interface GetDataServiceInterface
{
    public function getData():string;
}
Run Code Online (Sandbox Code Playgroud)

和服务

<?php

namespace App\Service;

use App\Interface\GetDataServiceInterface;

class GetJsonDataService implements GetDataServiceInterface
{
    public function getData():string
    {
        return getcwd();
    }
}
Run Code Online (Sandbox Code Playgroud)

但现在当我尝试提出请求时出现此错误

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"?
Run Code Online (Sandbox Code Playgroud)

我不确定还需要设置什么

bec*_*hir 14

您的控制器不会扩展,AbstractController因此您必须手动标记它,如下controller.service_arguments所示services.yaml

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