Sylius自定义控制器注入EntityManagerInterface失败报错求助
嗨,我看到你在Sylius自定义控制器里注入EntityManagerInterface时遇到这个500报错了,别着急,咱们来一步步排查解决问题~
先分析报错原因
你收到的报错信息已经给出了关键提示:
{"code":500,"message":"Could not resolve argument $em of "App\Controller\LicenceController::getlicencecodecrm()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?"}
看你services.yaml里的控制器配置,autowire: false并且没有添加controller.service_arguments标签,这就是导致依赖注入失败的核心原因——Symfony无法自动解析你控制器方法里的EntityManagerInterface参数。
解决方案
1. 修正控制器的服务配置
打开你的services.yaml,把LicenceController的配置改成这样:
App\Controller\LicenceController: autowire: true public: true tags: ['controller.service_arguments']
autowire: true:开启自动依赖注入,让Symfony自动识别并注入你需要的服务(比如EntityManagerInterface或者仓库类)tags: ['controller.service_arguments']:标记这是一个控制器,确保Symfony能正确处理控制器方法的参数注入
2. 更优雅的方式:直接注入LicenceRepository
既然你已经在sylius_ressource.yaml里配置了Licence的仓库,其实可以跳过EntityManager,直接注入LicenceRepository,这样更符合Sylius的资源设计理念,代码也更简洁:
修改LicenceController.php里的方法:
use App\Repository\LicenceRepository; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; public function getLicenceCodeCrm(Request $request, LicenceRepository $repo) { $criteria = $request->query->get('phrase'); $q = $criteria['search']['value']; $items = $repo->findByNamePart($q); return new JsonResponse([ '_embedded' => [ 'items' => $items, ] ]); }
3. 最后别忘了清除缓存
修改完配置后,执行缓存清除命令确保配置生效:
php bin/console cache:clear
这样调整之后,你应该就能正常获取仓库并执行查询了~
备注:内容来源于stack exchange,提问作者Giyash

