ThinkPHP 6 的 Service 目录应手动创建为 app/service(小写),对应命名空间 appservice,用于存放业务服务类;不可用 app/common 或 app/extend,因前者仅加载函数、后者属扩展包入口,且大小写不一致会导致 PSR-4 加载失败。

ThinkPHP 6 的 Service 目录位置是 app/service
ThinkPHP 6 默认不自带 service 目录,但官方推荐且社区通用做法是手动创建 app/service(注意是小写),与 app/controller、app/model 并列。该目录用于存放业务逻辑服务类,比如 UserAuthService、OrderPaymentService。
- 不要放在
app/common或app/extend:前者语义偏向全局辅助函数,后者是扩展包入口,都不符合服务层职责 - 不要命名为
services(复数)或Service(首字母大写):ThinkPHP 的自动加载器(基于 PSR-4)默认按目录名映射命名空间,app/service对应appservice命名空间,大小写不一致会导致类找不到 - 创建后需确保命名空间声明匹配,例如:
namespace appservice;
为什么不能直接用 app/common 放服务类
app/common 在 TP6 中默认被配置为「公共函数目录」,其下的 PHP 文件会被当作函数文件自动引入(通过 helper.php 类机制),而不是类自动加载路径。
- 若把
UserLogService.php放进app/common,即使写了class,也不会被 PSR-4 加载,调用时会报Class 'appcommonUserLogService' not found - 更隐蔽的问题是:如果误加了
use appcommonUserLogService,而该文件又没被显式include,运行时直接失败,且 IDE 很难提示
如何让 service 类被正确识别和使用
- 确保类文件命名与类名一致,如
app/service/PaymentService.php内必须是class PaymentService - 命名空间必须为
appservice(或子命名空间如appserviceorder,对应目录app/service/order) - 调用时可用依赖注入:
$payment = app()->make(ppservicePaymentService::class);
或在控制器构造函数中类型提示 - 若启用注解路由或 AOP,还需确认
service目录已加入扫描范围(默认未开启,一般无需改动)
TP5.1 和 TP6 的 service 目录差异
TP5.1 没有官方约定,常见项目自行建 application/common/service,命名空间多为 appcommonservice;而 TP6 统一收归到 app/service,并明确排除在「模块化」结构之外(即不支持按模块分 service,除非手动配置多个 PSR-4 映射)。
通过PCO Services API 管理 Planning Center Services 数据的 CLI 工具,包含计划、团队、歌曲和排班人员。
- 升级时若沿用 TP5.1 的
appcommonservice,必须在composer.json中补全 autoload:"psr-4": { "app\common\service\": "app/common/service/" } - 否则新项目里直接挪过去会 404 类 —— 这是最常被忽略的迁移断点
服务层目录本身不复杂,但命名空间、自动加载、版本差异这三点卡住的人最多。只要 app/service 存在、命名空间对、类名文件名一致,就基本不会出问题。
立即学习“PHP免费学习笔记(深入)”;


















