ThinkPHP6项目基操(9.架构分层)

一、分层意义

意义我觉得最重要的是方便维护,如果代码没有分层,都是写在控制器里,包括了各种参数校验,各种情景判断,各种数据查询返回结果不同,十分混乱,出现问题很难定位,修改需求十分头疼,良好的分层架构可以解决后顾之忧。

二、代码架构

在这里插入图片描述
这里借用了某课网老师的图,我又重新画了一遍,我们把代码分为以上5个模块,它们的作用分别为:

模块 作用
控制器 controller 负责调用业务层,返回组装数据给视图层或api接口
业务逻辑层 business 负责调用第三方库或模型层获取数据
基础库 lib 负责封装特定功能的库或引用第三方类库
模型层 model 负责连接数据库返回数据
视图层 view 负责返回数据到前台

三、common层设计

有些模块对于多个应用是可以公用的,所以可以创建一个common目录存放所有应用公共的文件,common目录与其他应用目录同级。如business、lib、model等。

注意:修改文件目录,记得修改文件命名空间和引用该文件的地方。
在这里插入图片描述
考虑到后面操作数据可能会用到redis等,所以这里对model再分层。

四、实践代码

Model:

<?php

namespace app\common\model\mysql;
use think\Model;

class Demo extends Model
{
    
    
    public function getDemoDataByCategoryId($cateId, $limit = 10){
    
    
        return $this->where("cate_id", $cateId)->limit($limit)->select()->toArray();
    }
}

Business:

<?php

namespace app\common\business;
use app\common\model\mysql\Demo as DemoModel;

class Demo
{
    
    
    public function getDemoDataByCategoryId($cateId, $limit = 10){
    
    
        $model = new DemoModel();
        $results = $model->getDemoDataByCategoryId($cateId, $limit);
        if(empty($results)){
    
    
            return [];
        }
        return $results;
    }
}

controller:

<?php

namespace app\demo\controller;

use app\BaseController;
use app\common\business\Demo;

class Index extends BaseController
{
    
    
    public function test(){
    
    
        $cateId = $this->request->param("cate_id",0,"intval");
        if(empty($cateId)){
    
    
            return show(config("status.error"), "参数错误");
        }
        $demo = new Demo();
        $results = $demo->getDemoDataByCategoryId($cateId);
        return show(config("status.success"), "ok", $results);
    }
}

猜你喜欢

转载自blog.csdn.net/zy1281539626/article/details/110411390
今日推荐