chengkun
2025-09-16 c2a5bb61d0dbca252c5111e0ebc8276c7cc68e26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
 
namespace app\home\controller;
 
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use app\BaseController;
use think\response\Json;
 
class Blog extends BaseController {
    public function index() {
        $list = Db::name('blog')->where('status', 1)->limit(10)->order('id desc')->select()->toArray();
        View::assign('list', $list);
        return View::fetch('index');
    }
    
    /**
     * 获取博客列表
     * @return Json
     */
    public function get_blog_list(): Json {
        try {
            if (!Request::isPost()) {
                throw new Exception('请求方式错误');
            }
            $list   = Db::name('blog')->where('status', 1)->limit(10)->order('id desc')->select()->toArray();
            $result = [
                'code'    => 200,
                'message' => '获取成功',
                'data'    => $list,
            ];
        } catch (Exception $exc) {
            $result = [
                'code'    => $exc->getCode(),
                'message' => $exc->getMessage(),
            ];
        }
        return json($result);
    }
    
    /**
     * 博客详情页
     * @param int $id
     * @return string
     */
    public function detail(int $id = 0): string {
        if (!$id || !is_numeric($id)) {
            $this->error('参数错误');
        }
        // $info = Db::name('blog')->where('id', $id)->find();
        // if (!$info) {
        //     $this->error('数据不存在');
        // }
        // View::assign('info', $info);
        View::assign('id', $id);
        return View::fetch('detail');
    }
    
    /**
     * 获取博客内容
     * @return Json
     */
    public function get_blog_info(): Json {
        try {
            $id = input('id', 0);
            if (!$id || !is_numeric($id)) {
                throw new Exception('参数错误');
            }
            $info = Db::name('blog')->where('id', $id)->find();
            if (!$info) {
                throw new Exception('数据不存在');
            }
            $result = [
                'code'    => 200,
                'message' => '获取成功',
                'data'    => $info,
            ];
        } catch (Exception $exc) {
            $result = [
                'code'    => $exc->getCode(),
                'message' => $exc->getMessage(),
            ];
        }
        return json($result);
    }
}