php swoft 中的数据分层
不仅仅局限于 MVC 。将数据在model 这一个层面剖析开,优雅的处理数据 逻辑,缓存,业务,数据库操作的烦恼。
这个思路也适用于 thinkphp,hyperf,imi 等框架。不再简单的 实现 controller->model->view 的处理过程。
简化代码,每一层清晰地定义相应处理的数据。
controller 层面
<?php declare(strict_types=1); /** * This file is part of Swoft. * * @link https://swoft.org * @document https://swoft.org/docs * @contact group@swoft.org * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE */ namespace App\Http\Controller; use Swoft; use Swoft\Http\Message\ContentType; use Swoft\Http\Message\Response; use Swoft\Http\Server\Annotation\Mapping\Controller; use Swoft\Http\Server\Annotation\Mapping\RequestMapping; use Swoft\Http\Server\Annotation\Mapping\RequestMethod; use Swoft\Http\Message\Request; use Swoft\View\Renderer; use Throwable; use function context; use App\Model\Data\HomeData; /** * Class HomeController * @Controller("/Home") */ class HomeController { /** * @RequestMapping("/Home/HomeTest",method={RequestMethod::GET}) * * @return Response */ public function HomeTest() { $request = context()->getRequest(); $HomeData = new HomeData(); $Detail = $HomeData->DataTest(); $res = Result(200, '获取成功', $Detail); return context()->getResponse()->withData($res); } }
Data 层中 进行缓存判断,资源调用。
<?php declare(strict_types=1); /** * This file is part of Swoft. * * @link https://swoft.org * @document https://swoft.org/docs * @contact group@swoft.org * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE */ namespace App\Model\Data; use App\Model\Dao\HomeDao; use App\Model\Entity\Home; use Swoft\Redis\Exception\RedisException; use Swoft\Redis\Pool; use Swoft\Redis\Redis; class HomeData { public function DataTest(){ $ReductionRedis = Redis::rawCommand('GET', 'FullReduction'); $ReductionInfo = json_decode($ReductionRedis, true); if (empty($ReductionInfo)) { $HomeDao = new HomeDao(); $ReductionInfo = $HomeDao->HomeDaoTest(); } return $ReductionInfo; } }
Dao层,返回数据。操作实例。 【Entity】中,就是直接指定数据文件了。
<?php declare(strict_types=1); /** * This file is part of Swoft. * * @link https://swoft.org * @document https://swoft.org/docs * @contact group@swoft.org * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE */ namespace App\Model\Dao; use Swoft\Redis\Pool; use Swoft\Redis\Redis; use App\Model\Entity\Home; class HomeDao { public function HomeDaoTest(){ $Home = new Home(); $DailyActivity = $Home->DailyActivity(); return $DailyActivity; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现