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

Symfony DI服务中命名参数传null导致类加载失败的问题

问题:Symfony services.xml中使用命名参数传递null值失败

我有一个无法修改的类,其构造函数代码如下:

/**
 * @param int|null $maxBodyLength
 * @param string   $binaryDetectionRegex By default, this is all non-printable ASCII characters and <DEL> except for \t, \r, \n
 */
public function __construct($maxBodyLength = 1000, string $binaryDetectionRegex = '/([\x00-\x09\x0C\x0E-\x1F\x7F])/')
{
    $this->maxBodyLength = $maxBodyLength;
    $this->binaryDetectionRegex = $binaryDetectionRegex;
}

我希望通过services.xml将$maxBodyLength设置为null。使用位置参数的配置可以正常工作:

<service id="meteor.api_logger.formatter" class="Http\Message\Formatter\FullHttpMessageFormatter">
    <argument>null</argument>
</service>

但使用命名参数配置时却抛出错误:

<service id="meteor.api_logger.formatter" class="Http\Message\Formatter\FullHttpMessageFormatter">
    <argument key="$maxBodyLength">null</argument>
</service>

错误信息:

In AbstractRecursivePass.php line 174:

  Invalid service "meteor.api_logger.formatter": class "Http\Message\Formatter\FullHttpMessageFormatter" does not exist.

我已经尝试了以下方法,但均出现相同错误:

  • 在services.xml中同时传递另一个参数
  • 移除key中的$符号
  • 使用0替代null
  • 使用<argument key="$maxBodyLength"/>

解决方案

出现该错误的核心原因是:使用命名参数时,Symfony DI容器要求参数名不带$符号,且直接写null会被解析为字符串而非PHP原生null,同时参数配置错误可能导致容器无法正确识别类的元数据,触发"类不存在"的误导性提示。

正确的配置方式如下:

<service id="meteor.api_logger.formatter" class="Http\Message\Formatter\FullHttpMessageFormatter">
    <argument key="maxBodyLength" null="true"/>
</service>

关键要点:

  1. 参数名去掉$:Symfony处理命名参数时,使用构造函数中定义的参数名(如maxBodyLength),不需要加前缀$。
  2. 用null="true"指定空值:<argument>null</argument>会被解析为字符串"null",必须通过null="true"属性来传递PHP的null值。
  3. 类存在性验证:确保Http\Message\Formatter\FullHttpMessageFormatter已通过Composer正确安装,命名空间配置无误——修复参数配置后,容器能正常解析类元数据,"类不存在"的错误通常会自动消失。

如果需要同时传递第二个命名参数,配置示例:

<service id="meteor.api_logger.formatter" class="Http\Message\Formatter\FullHttpMessageFormatter">
    <argument key="maxBodyLength" null="true"/>
    <argument key="binaryDetectionRegex">/自定义正则表达式/</argument>
</service>

内容的提问来源于stack exchange,提问作者O'Niel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:23:10