控制器开发
分层架构
| 层级 | 职责 | 示例 |
|---|---|---|
| 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 门面。