Code前端首页关于Code前端联系我们

thinkphp6.x API接口开发一个简单的小例子

terry 2年前 (2023-09-24) 阅读数 59 #后端开发

对于从未接触过接口开发的小朋友PHP来说,即:前端发送商品ID,返回商品详情;无需身份验证或其他任何东西,只需使用它来了解流程并聪明地开始

通过一个简单的小示例开始

API接口开发 - 基于thinkphp6。请求端)controller/index.php:

<?php namespace app\controller;use app\BaseController;class Index extends BaseController {        //前端视图public function index() {return view();}//提交查询入口public function api_chaxun() {// http协议请求$url = 'http://localhost/index.php/index/goods/api/';// input('goods_id') 是前端的from传过来的name值$ch = curl_init($url.'?goods_id='.input('goods_id'));curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);// 执行 并把执行后的数据赋值给 $data$data = curl_exec($ch);// 关闭curl_close($ch);// 返回数据return $data;}}

第三步:API接口端,code/itemcontroller.php:

<?php namespace app\controller;use app\BaseController;use think\facade\Db;class Goods extends BaseController {/** 客户端提交商品ID(goods_id)给API* API返回此商品信息**/public function api($goods_id=1) {// 查询 并把数据赋值给 $data$data = Db::name('goods')->where('id',$goods_id)->find();// 返回数据return json($data);//print_r($data);}}

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门