Symfony 6自定义URL匹配器注册失败:服务不存在错误排查
Symfony 6 自定义URL匹配器服务不存在异常解决办法
在Symfony 6中注册自定义URL匹配器时,抛出如下异常:
Service "App\Routing\QueryStringUrlMatcher" not found: the container inside "Symfony\Component\DependencyInjection\Argument\ServiceLocator" is a smaller service locator that only knows about the "kernel" service.
问题原因
framework.yml路由配置错误:指定type: service时,resource需填服务ID而非类名,当前配置用了自定义匹配器的类名,但容器内注册的服务ID是url_matcher。- Symfony 6默认所有服务为私有状态,路由组件无法访问私有服务,因此需要将自定义匹配器服务设为公开。
解决方案
1. 修正config/packages/framework.yml路由配置
将router.resource改为已注册的服务ID@url_matcher:
framework: router: resource: '@url_matcher' type: service
2. 调整config/services.yml服务配置
添加public: true让服务可被路由组件访问,同时移除不必要的router.matcher标签(该标签用于链式匹配器场景,替换默认匹配器时无需使用):
services: url_matcher: class: App\Routing\QueryStringUrlMatcher arguments: - '@router.default' - '@router.request_context' public: true
3. 优化自定义匹配器逻辑(可选)
可以简化matchRequest方法,直接复用父类逻辑,避免手动操作$this->request:
namespace App\Routing; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\RouterInterface; class QueryStringUrlMatcher extends UrlMatcher { public function __construct(RouterInterface $router, RequestContext $context) { parent::__construct($router->getRouteCollection(), $context); } public function matchRequest(Request $request): array { // 在这里添加自定义匹配逻辑,比如基于查询字符串的路由匹配规则 return parent::matchRequest($request); } }
内容的提问来源于stack exchange,提问作者user2497818
相关产品推荐
相关产品推荐

