搜索

苹果cms二次开发自定义API教程

作者 : 影视站长圈 发布时间:2022-11-16 人阅读

苹果cms后台自带api功能,可以给前端提供一些数据,但是api能力不是非常全面,需要自定义接口,那么如何来自定义接口呢?有两种方式实现:

第一种方法:新增控制器:

在application/api/controller这个目录下创建一个Test.php文件如下:

Test.php

PS:文件名一定要大写开头,tp5就是这么决定的,咱也不知道为啥!!

<?php
namespace app\api\controller;
use think\Controller;
use think\Cache;
 
class Test extends Base
{
    var $_param;
    public function __construct()
    {
      parent::__construct();
      $this->_param = $this->request->param();
    }
 
    public function index()
    {
      $data = [];
      $list = ['code'=>0,'data'=>$data]
      return json($list);
    }
 
}

这样第一步我们就完成了,可通过域名+/api.php/test进行访问

以上仅仅是创建了接口控制器,接口一定是要请求我们cms里面的数据,例如影片数据。

      $lp = $this->request->param();//请求的参数
      $where = [];
      $where['type_id']= $lp['type'];//分类id
      $order ='vod_time desc';//排序
      $page = $lp['page'];//页数
      $limit = $lp['num'];//数量
      $data = model('Vod')->listData($where,$order,$page,$limit);
      $list = ['code'=>0,'data'=>$data];
      return json($list);

这时候我们通过 http://www.xxx.com/api.php/test?type=1&page=1&num=20 get请求就可以输出json数据了,当然也可以post请求。

第二种方法:模板自定义php功能:

1.在全局引入include.html 模板中加入

 {php}require MAC_ROOT_TEMPLATE . 'php/function.php'{/php}

2.在html中创建php文件夹和function.php文件

function.php

<?php 
 
function vod(){
    $param = input();
    $param['page'] = intval($param['page']) < 1 ? 1 : intval($param['page']);
    $param['limit'] = intval($param['limit']) < 20 ? 20 : intval($param['limit']);
    $where = [];
    $where['vod_type'] = $param['type'];
    $order ='vod_time desc';//排序
    $res = model('Vod')->listData($where, $order, $param['page'], $param['limit']);
    return json($res['list']);
};

3.接着在label自定义模板目录中中创建api.html

api.html

{include file="public/include"}

//或者

{php}require MAC_ROOT_TEMPLATE . 'php/function.php'{/php}
{:vod()}//执行函数

最后通过域名http://www.xxx.com/index.php/label/api.html?type=1&page=1&limit=20 请求接口


标签