必须安装phpdocumentor/phpdocumentor为开发依赖,配置phpdoc.xml限定源码路径并排除无关目录,通过composer.json scripts固化命令,注意注释规范与缓存优化。

用 phpdocumentor 生成 API 文档前必须确认的依赖项
Composer 本身不生成文档,真正干活的是 phpdocumentor/phpdocumentor。你得先把它作为开发依赖装进项目里,而不是全局安装——否则 CI/CD 流水线或他人本地构建时容易失败。
- 运行
composer require --dev phpdocumentor/phpdocumentor(v3 推荐,PHP 7.4+) - 确保
vendor/bin/phpdoc可执行;若报错“command not found”,检查vendor/bin/是否在$PATH中,或直接用php vendor/bin/phpdoc - v2 已停止维护,别再用
phpdocumentor/phpdocumentor:2.*,它不支持 PHP 8.1+ 的属性语法(如#[\Attribute])
配置 phpdoc.xml 避免扫描错误目录
默认会扫整个项目,把 tests/、vendor/、build/ 也塞进文档里,结果是生成巨慢 + 报一堆“找不到父类”警告。必须显式限定源码路径和排除规则。
<?xml version="1.0" encoding="UTF-8" ?>
<phpdocumentor
configVersion="3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://www.phpdoc.org"
xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/phpDocumentor/phpDocumentor/v3/data/xsd/phpdoc.xsd"
>
<paths>
<output>docs/api</output>
<cache>docs/cache</cache>
</paths>
<project>
<filesets>
<fileset name="source">
<directory>src</directory>
<exclude>src/Tests</exclude>
<exclude>src/Example</exclude>
</fileset>
</filesets>
</project>
</phpdocumentor>-
<directory></directory>值必须是相对于phpdoc.xml所在路径的相对路径,不是 Composer 根目录 - 排除路径用
<exclude></exclude>,不是正则;写tests/不如写src/Tests明确 - 输出目录(
<output></output>)建议设为docs/api,方便 GitHub Pages 直接托管
在 composer.json 的 scripts 里加一键命令
把生成逻辑固化到 composer.json,别人 clone 代码后只需 composer install && composer docs,不用翻 README 记命令。
"scripts": {
"docs": [
"php vendor/bin/phpdoc --config=phpdoc.xml",
"chmod -R a+r docs/api"
]
}- 第二行
chmod是给 CI 用的:某些 Linux 环境生成的 HTML 文件权限为 600,GitHub Pages 无法读取 - 不要写成
"docs": "php vendor/bin/phpdoc --config=phpdoc.xml 2>&1"—— 屏蔽错误会掩盖真实问题,比如注释语法写错(@param string $foo漏了变量名) - 如果想每次
git push后自动更新文档,CI 配置里调用composer docs即可,无需额外 shell 脚本
常见报错与绕过技巧
生成失败时,90% 出在注释格式或符号解析上,而不是代码本身。
立即学习“PHP免费学习笔记(深入)”;
-
Unable to find the class "FooInterface":说明use语句缺失,或接口没被 autoload 加载;检查composer.json的"autoload"是否覆盖了src/下所有命名空间 -
Invalid tag "@return void":v3 默认禁用@return void,删掉即可;void 类型函数不必写@return - 生成 HTML 很慢?加
--cache-folder=docs/cache复用缓存,首次之后快 3–5 倍 - 想跳过某个类不生成文档?在类 DocBlock 顶部加
/** @internal */,phpDocumentor 会自动忽略
文档生成不是一劳永逸的事,只要改了 public 方法签名或新增了接口,就得重新跑一次。把 composer docs 嵌进 pre-commit hook 或 CI,比靠人想起来更可靠。










