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

MPDF 8手动集成至PHP 8环境时类型错误问题求助

升级MPDF 6到适配PHP 8的MPDF 8时的TypeError问题

问题描述

手动将MPDF 8文件下载至application\third-party目录,将Psr\log下载至application\psr\log目录,修改Mpdf.php中的路径后触发如下TypeError:

未捕获异常:类型错误
信息:Mpdf\ServiceFactory::getServices(): 参数#2 ($logger)必须为psr\log\Psr\Log\LoggerInterface类型,传入的是Psr\Log\NullLogger,调用位置在D:\wamp\www\test\application\third_party\Mpdf\Mpdf.php第1092行
文件名:D:\wamp\www\test\application\third_party\Mpdf\ServiceFactory.php
行号:44

相关代码片段

Mpdf.php出错部分

$this->logger = new NullLogger();

$originalConfig = $config;
$config = $this->initConfig($originalConfig);

$serviceFactory = new ServiceFactory($container);
$services = $serviceFactory->getServices(
    $this,
    $this->logger,
    $config,
    $this->languageToFont,
    $this->scriptToLanguage,
    $this->fontDescriptor,
    $this->bmp,
    $this->directWrite,
    $this->wmf
);

NullLogger.php代码

<?php

namespace Psr\Log;

/**
 * This Logger can be used to avoid conditional log calls.
 *
 * Logging should always be optional, and if no logger is provided to your
 * library creating a NullLogger instance to have something to throw logs at
 * is a good way to avoid littering your code with `if ($this->logger) { }`
 * blocks.
 */
require_once APPPATH . 'third_party/psr/log/src/Psr/Log/AbstractLogger.php';
class NullLogger extends AbstractLogger
{
    /**
     * Logs with an arbitrary level.
     *
     * @param mixed[] $context
     *
     * @throws \Psr\Log\InvalidArgumentException
     */
    public function log($level, string|\Stringable $message, array $context = []): void
    {
        // noop
    }
}

解决方案

1. 修正ServiceFactory中的命名空间错误

错误提示里的psr\log\Psr\Log\LoggerInterface是重复的错误命名空间,正确的应该是Psr\Log\LoggerInterface。打开ServiceFactory.php,找到getServices方法的参数声明,将$logger的类型提示修正为\Psr\Log\LoggerInterface。

2. 确保Psr Log的自动加载逻辑正确

  • 不要用硬编码的require_once,推荐通过Composer管理依赖:执行composer require psr/log,让Composer自动处理命名空间映射和自动加载,避免手动放置文件导致的路径混乱。
  • 若无法使用Composer,需确保application\psr\log目录被添加到PHP的include_path,且目录结构严格匹配命名空间(Psr\Log对应application/psr/log/src/Psr/Log)。

3. 修正Mpdf.php中的Logger实例化逻辑

在Mpdf.php顶部添加正确的命名空间引用:

use Psr\Log\NullLogger;

再执行实例化操作,确保命名空间解析正确。

4. 优先用Composer安装MPDF 8

手动下载容易遗漏依赖或配置错误,直接通过Composer安装MPDF 8:

composer require mpdf/mpdf

Composer会自动安装所有适配的依赖组件(包括正确版本的Psr Log),并配置好自动加载,彻底避免手动部署的各类问题。


内容的提问来源于stack exchange,提问作者THUSHARA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:10:10