Symfony控制器无法从容器获取:是否遗漏controller.service_arguments标签?
解决Symfony控制器不可调用及依赖注入问题
问题1:控制器私有无法被容器获取
报错提示Controller "App\Controller\ApiController" cannot be fetched from the container because it is private,原因是Symfony默认将src/下的类注册为私有服务,而控制器需要被路由组件调用,需标记为可调用的控制器服务。
解决方法(二选一即可)
方法1:使用#[AsController]属性(Symfony 5.3+推荐)
在ApiController类上添加#[AsController]属性,明确告知Symfony这是一个控制器服务:
<?php namespace App\Controller; use App\Interface\GetDataServiceInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Attribute\AsController; #[AsController] #[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() ); } }
方法2:在services.yml中添加控制器标签
在services.yml里为控制器类添加controller.service_arguments标签,也可批量配置所有控制器:
services: # ... 原有配置 # 单个控制器配置 App\Controller\ApiController: tags: ['controller.service_arguments'] # 或者批量配置所有Controller目录下的类 App\Controller\: resource: '../src/Controller/' tags: ['controller.service_arguments']
问题2:接口实现类的命名空间拼写错误
你的services.yml中接口映射的服务ID存在拼写错误:
# 错误写法(多了一个s) App\Interface\GetDataServiceInterface: '@App\Services\GetJsonDataService' # 正确写法(对应实际类的命名空间App\Service\GetJsonDataService) App\Interface\GetDataServiceInterface: '@App\Service\GetJsonDataService'
该错误会导致依赖注入失败,即使控制器问题解决后也会出现服务找不到的报错,必须修正。
最终验证
修改完成后,清除Symfony缓存:
php bin/console cache:clear
重新请求/api/products即可正常访问。
内容的提问来源于stack exchange,提问作者a_dv85
相关产品推荐
相关产品推荐

