控制器开发

分层架构

层级职责示例
Controller接收请求、返回响应app/index/controller/News.php
Service业务逻辑层app/common/service/ContentService.php
Model数据模型层app/common/model/Product.php
Helper助手函数app/common.php

控制器示例

namespace app\index\controller; use app\index\BaseController; use think\facade\View; use think\facade\Db; class Example extends BaseController { public function index() { // 方式1: 使用助手函数(推荐) $products = getProduct(10, 0, 'id desc'); $categories = getCat(0, 'product'); // 方式2: 使用 Service 层 $news = ContentService::getNewsByCat(0, 10); // 方式3: 使用 Model $item = ProductModel::where('id', $id)->find(); // 方式4: 使用 Db 门面 $list = Db::name('news')->where('delstatus', 0)->select(); View::assign(['products' => $products]); return View::fetch(); } }

最佳实践

优先使用助手函数(最简洁),复杂业务逻辑用 Service 层,自定义查询用 Db 门面。