在开发中大型ThinkPHP6项目时,合理的分层架构设计能够显著提高代码的可维护性、可扩展性和可测试性。本文将详细介绍如何在ThinkPHP6项目中实现清晰的分层架构。
ThinkPHP默认采用MVC(Model-View-Controller)架构,但随着项目复杂度增加,这种简单的分层可能面临以下问题:
我们推荐采用以下分层架构:
app
├── controller // 控制器层
├── service // 业务服务层
├── repository // 数据访问层
├── model // 模型层
├── validate // 验证层
└── exception // 异常处理层
职责:接收请求、参数验证、调用服务、返回响应
// app/controller/UserController.php
namespace app\controller;
use app\service\UserService;
use think\response\Json;
class UserController
{
protected $userService;
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
public function info(int $id): Json
{
$user = $this->userService->getUserInfo($id);
return json($user);
}
}
职责:处理业务逻辑,协调多个Repository和Model
// app/service/UserService.php
namespace app\service;
use app\repository\UserRepository;
use app\exception\UserException;
class UserService
{
protected $userRepo;
public function __construct(UserRepository $userRepo)
{
$this->userRepo = $userRepo;
}
public function getUserInfo(int $id): array
{
$user = $this->userRepo->findById($id);
if (!$user) {
throw new UserException('用户不存在');
}
return [
'id' => $user->id,
'name' => $user->name,
'avatar' => $user->avatar
];
}
}
职责:数据访问逻辑,数据库操作封装
// app/repository/UserRepository.php
namespace app\repository;
use app\model\User;
use think\db\Query;
class UserRepository
{
protected $userModel;
public function __construct(User $userModel)
{
$this->userModel = $userModel;
}
public function findById(int $id): ?User
{
return $this->userModel->where('id', $id)
->where('status', 1)
->find();
}
public function getPaginatedList(int $pageSize = 10): Query
{
return $this->userModel->where('status', 1)
->order('create_time', 'desc')
->paginate($pageSize);
}
}
职责:数据表映射,基础字段定义,简单查询
// app/model/User.php
namespace app\model;
use think\Model;
class User extends Model
{
// 设置当前模型对应的完整数据表名称
protected $table = 'users';
// 设置字段信息
protected $schema = [
'id' => 'int',
'name' => 'string',
'email' => 'string',
'create_time' => 'datetime',
'update_time' => 'datetime',
'status' => 'int'
];
// 定义时间戳字段名
protected $createTime = 'create_time';
protected $updateTime = 'update_time';
// 状态枚举
const STATUS_ACTIVE = 1;
const STATUS_BANNED = 0;
}
职责:请求参数验证
// app/validate/UserValidate.php
namespace app\validate;
use think\Validate;
class UserValidate extends Validate
{
protected $rule = [
'name' => 'require|max:25',
'email' => 'require|email',
];
protected $message = [
'name.require' => '名称必须',
'name.max' => '名称最多不能超过25个字符',
'email.require' => '邮箱必须',
'email.email' => '邮箱格式错误',
];
// 场景验证
protected $scene = [
'edit' => ['name', 'email'],
];
}
职责:自定义业务异常
// app/exception/UserException.php
namespace app\exception;
use think\Exception;
class UserException extends Exception
{
protected $code = 404;
protected $message = '用户不存在';
public function __construct(string $message = "", int $code = 0)
{
$this->message = $message ?: $this->message;
$this->code = $code ?: $this->code;
parent::__construct($this->message, $this->code);
}
}
ThinkPHP6的依赖注入容器使得分层架构更易实现:
// 控制器依赖服务层
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
// 服务层依赖仓库层
public function __construct(UserRepository $userRepo)
{
$this->userRepo = $userRepo;
}
// 仓库层依赖模型
public function __construct(User $userModel)
{
$this->userModel = $userModel;
}
// UserController.php
public function create(): Json
{
// 参数验证
$params = request()->post();
validate(UserValidate::class)->scene('create')->check($params);
try {
$user = $this->userService->createUser($params);
return json(['code' => 200, 'data' => $user]);
} catch (UserException $e) {
return json(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
}
}
// UserService.php
public function createUser(array $data): array
{
// 检查邮箱是否已存在
if ($this->userRepo->existsByEmail($data['email'])) {
throw new UserException('邮箱已存在', 400);
}
// 创建用户
$user = $this->userRepo->create($data);
// 发送欢迎邮件
$this->sendWelcomeEmail($user);
return $user->toArray();
}
// UserRepository.php
public function existsByEmail(string $email): bool
{
return $this->userModel->where('email', $email)->count() > 0;
}
public function create(array $data): User
{
return $this->userModel->create($data);
}
合理的分层架构是构建可维护、可扩展ThinkPHP6应用的关键。通过Controller-Service-Repository-Model的分层设计,配合验证层和异常处理层,可以构建出结构清晰、易于维护的应用程序。在实际开发中,应根据项目规模和团队习惯适当调整分层策略,找到最适合项目的架构方案。