You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

问题原因

  1. framework.yml路由配置错误:指定type: service时,resource需填服务ID而非类名,当前配置用了自定义匹配器的类名,但容器内注册的服务ID是url_matcher。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:23:14