学习thinkphp5返回App文章列表页面支持关键词搜索、分页、分类api接口整理

封装常用函数common

在这里插入图片描述

common.php

<?php


// 应用公共文件

function pagination($obj)
{
    
    
    if (!$obj) {
    
    
        return '';
    }
    //得到参数,并传递
    $params = request()->param();
    return '<div class="qipa250-app">' . $obj->appends($params)->render() . '</div>';
}

/**
 * 获取栏目名称
 * @param $catId
 */
function getCatName($catId)
{
    
    
    if (!$catId) {
    
    
        return '';
    }
    $cats = config('category.category_list');

    return !empty($cats[$catId]) ? $cats[$catId] : '';
}

//常用数字转换方法 将1和0 转换成对应的文字
function isYesNo($str)
{
    
    
    return $str ? '<span style="color:red"> 是</span>' : '<span > 否</span>';
}

/**
 * 状态
 * @param $id
 * @param $status
 */
function status($id, $status)
{
    
    
    $controller = request()->controller();

    $sta = $status == 1 ? 0 : 1;
    $url = url($controller . '/status', ['id' => $id, 'status' => $sta]);

    if ($status == 1) {
    
    
        $str = "<a href='javascript:;' title='修改状态' status_url='" . $url . "' οnclick='app_status(this)'><span class='label label-success radius'>正常</span></a>";
    } elseif ($status == 0) {
    
    
        $str = "<a href='javascript:;' title='修改状态' status_url='" . $url . "' οnclick='app_status(this)'><span class='label label-danger radius'>待审</span></a>";
    }

    return $str;
}

/**
 * 通用化API接口数据输出
 * @param int $status 业务状态码
 * @param string $message 信息提示
 * @param [] $data  数据
 * @param int $httpCode http状态码
 * @return array
 */
function show($status, $message, $data = [], $httpCode = 200)
{
    
    
    $data = [
        'status' => $status,
        'message' => $message,
        'data' => $data,
    ];

    return json($data, $httpCode);
}

后台创建文章控制器

在这里插入图片描述

News.php

<?php

namespace app\api\controller;

use app\api\controller\Common;

//封装的异常报错类
use app\common\lib\exception\ApiException;

class News extends Common
{
    
    

    public function index()
    {
    
    
        //得到提交的数据
        $data = input('get.');
        //组合where条件
        $whereData['status'] = config('code.status_normal');
        //如果有类型id
        if (!empty($data['catid'])) {
    
    
            $whereData['catid'] = input('get.catid', 0, 'intval');
        }
        //如果有搜索的title关键词
        if (!empty($data['title'])) {
    
    
            $whereData['title'] = ['like', '%' . $data['title'] . '%'];
        }
        $this->getPageAndSize($data);
        $total = model('News')->getNewsCountByCondition($whereData);
        $news = model('News')->getNewsByCondition($whereData, $this->from, $this->size);
        $result = [
            'total' => $total,
            'page_num' => ceil($total / $this->size),
            'list' => $this->getDealNews($news),
        ];
        return show(0, '', $result);
    }
 
}

公共控制器方法

在这里插入图片描述
Common.php

<?php

namespace app\api\controller;

use app\common\lib\ApiAuth;
use app\common\lib\Time;
use think\Controller;

use app\common\lib\exception\ApiException;

use app\common\lib\Aes;

use think\cache\driver\Redis;

/*
 * api接口模块的公共控制器
 */

class Common extends Controller
{
    
    


    //设置默认值
    public $page = 1;
    public $size = 10;
    public $from = 0;


    /**
     * 获取分页page size 内容
     */
    public function getPageAndSize($data)
    {
    
    
        $this->page = !empty($data['page']) ? $data['page'] : 1;
        $this->size = !empty($data['size']) ? $data['size'] : config('paginate.list_rows');
        $this->from = ($this->page - 1) * $this->size;
    }

}

常用config公共配置文件

在这里插入图片描述
code.php

<?php
/**
 * Created by PhpStorm.
 * User: baidu
 * Date: 17/7/29
 * Time: 下午11:24
 */

/**
 * 和状态码相关的文案配置
 */
return [
    'status_delete' => -1,
    'status_normal' => 1,
    // 待审
    'status_padding' => 0,

    'success' => 1,
    'error' => 0,
];

文章分类配置文件category.php

<?php

//后台资讯栏目,应该用表来维护,现在是用公共配置文件的数组
return [
    'category_list' => array(
        '1' => '综艺',
        '2' => '重要',
        '3' => '音乐',
    ),
];

model层配置对应方法

<?php

namespace app\common\model;

use think\Model;
use app\common\model\Base;

class News extends Base
{
    
    

    /**
     * 后台自动化分页
     * @param array $data
     */
    public function getNews($data = [])
    {
    
    
        $data['status'] = [
            'neq', config('code.status_delete')
        ];

        $order = ['id' => 'desc'];
        // 查询

        $result = $this->where($data)
            ->order($order)
            ->paginate();
        // 调试
        echo $this->getLastSql();

        return $result;
    }


    /**
     * 根据来获取列表的数据
     * @param array $param
     */
    public function getNewsByCondition($condition = [], $from = 0, $size = 5)
    {
    
    
        if (!isset($condition['status'])) {
    
    
            $condition['status'] = [
                'neq', config('code.status_delete')
            ];
        }

        $order = ['id' => 'desc'];

        $result = $this->where($condition)
            ->field($this->_getListField())
            ->limit($from, $size)
            ->order($order)
            ->select();
        //  echo $this->getLastSql();
        return $result;
    }

    /**
     * 根据条件来获取列表的数据的总数
     * @param array $param
     */
    public function getNewsCountByCondition($condition = [])
    {
    
    
        if (!isset($condition['status'])) {
    
    
           //neq表示不等于 配置文件中的 删除的文章状态
            $condition['status'] = [
                'neq', config('code.status_delete')
            ];
        }

        return $this->where($condition)
            ->count();
        //echo $this->getLastSql();
    }

    /**
     * 获取首页头图数据
     * @param int $num
     * @return array
     */
    public function getIndexHeadNormalNews($num = 4)
    {
    
    
        //条件
        $where = [
            'status' => 1,
            'is_head_figure' => 1,
        ];

        //排序方式
        $order = ['id' => 'desc'];
        //查询
        return $this->where($where)
            ->field($this->_getListField())
            ->order($order)
            ->limit($num)
            ->select();


    }


    /**
     * 获取推荐的数据
     */
    public function getPositionNormalNews($num = 20)
    {
    
    
        $where = [
            'status' => 1,
            'is_position' => 1,
        ];
        $order = [
            'id' => 'desc',
        ];
        return $this->field($this->_getListField())
            ->where($where)
            ->order($order)
            ->limit($num)->select() ?: [];
    }

    /**
     * 获取排行榜数据
     * @param int $num
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getRankNormalNews($num = 5)
    {
    
    
        $data = [
            'status' => 1,
        ];

        $order = [
            'read_count' => 'desc',
        ];

        return $this->where($data)
            ->field($this->_getListField())
            ->order($order)
            ->limit($num)
            ->select();
    }


    /**
     * 通用化获取参数的数据字段
     */
    private function _getListField()
    {
    
    
        return [
            'id',
            'catid',
            'image',
            'title',
            'read_count',
            'status',
            'is_position',
            'update_time',
            'create_time'
        ];
    }
}

配置访问文章列表的路由

在这里插入图片描述

route.php

<?php
//引用think的路由底层Route类
use think\Route;

//新闻资讯列表 使用resource 包含了多种请求方式get\post\等
Route::resource('api/news', 'api/news');

postman请求测试

1、不传任何参数get请求

在这里插入图片描述

2、传入类型catid

http://app.thinkphpwu.com/api/news?catid=2
在这里插入图片描述

3、传入分页

第1页
在这里插入图片描述第2页
在这里插入图片描述

4、传入标题title搜索

在这里插入图片描述

5、分类、分页、数量、标题

http://app.thinkphpwu.com/api/news?catid=3&page=1&size=2&title=qipa250

size=2,控制显示条数
在这里插入图片描述http://app.thinkphpwu.com/api/news?catid=3&page=1&size=1&title=qipa250

size=1,显示1条数据
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/guo_qiangqiang/article/details/112394348