学习thinkphp5文章详情页面接口开发

学习thinkphp5文章详情页面接口开发

接口请求的控制器

<?php

namespace app\api\controller;

use app\api\controller\Common;

use app\common\lib\exception\ApiException;


class News extends Common
{
    
    

    /**
     * 获取详情接口
     */
    public function read()
    {
    
    
        // 详情页面 APP -》 1、x.com/3.html  2、 接口
        $id = input('param.id', 0, 'intval');
        if (empty($id)) {
    
    
            return new ApiException('id is not ', 404);
        }

        // 通过id 去获取数据表里面的数据
        // try catch untodo
        $news = model('News')->get($id);
        if (empty($news) || $news->status != config('code.status_normal')) {
    
    
            return new ApiException('不存在该新闻', 404);
        }

        //修改文章的阅读数量自加1
        try {
    
    
            model('News')->where(['id' => $id])->setInc('read_count');
        } catch (\Exception $e) {
    
    
            return new ApiException('error', 400);
        }

        $cats = config('category.category_list');
        $news->catname = $cats[$news->catid];
        return show(config('code.success'), 'OK', $news, 200);
    }
}

postman请求测试

http://app.thinkphpwu.com/api/news/16

在这里插入图片描述随便编一个id
http://app.thinkphpwu.com/api/news/16677 就会报错
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/guo_qiangqiang/article/details/112395618
今日推荐