我創建了這個控制器
<?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()
);
}
}
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'
這是界面
<?php
namespace App\Interface;
interface GetDataServiceInterface
{
public function getData():string;
}
和服務
<?php
namespace App\Service;
use App\Interface\GetDataServiceInterface;
class GetJsonDataService implements GetDataServiceInterface
{
public function getData():string
{
return getcwd();
}
}
但是現在當我嘗試發出請求時出現此錯誤
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"?
我不確定我還需要設定什么
uj5u.com熱心網友回復:
您的控制器沒有擴展,AbstractController因此您必須手動標記controller.service_arguements它services.yaml
https://symfony.com/doc/current/controller/service.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521212.html
