Home php教程 php手册 使用Thinkphp框架开发移动端接口

使用Thinkphp框架开发移动端接口

Jun 06, 2016 pm 07:48 PM
php

本文给大家分享的是使用thinkphp框架开发移动端接口的2种方法,一种是开发API,另外一种是实现移动端访问自动切换移动主题模板,从而实现伪app访问,下面我们就

方案一:给原生APP提供api接口

使用TP框架时 放在common文件夹下文件名就叫function.php

'Success', 'msg' => $msg, 'data' =>$data ); print json_encode($result); } /** * @param null $msg 返回具体错误的提示信息 * @param flag success CURD 操作失败 * Function descript:返回标志信息 ‘Error',和提示信息的json 数组 */ function returnApiError($msg = null){ $result = array( 'flag' => 'Error', 'msg' => $msg, ); print json_encode($result); } /** * @param null $msg 返回具体错误的提示信息 * @param flag success CURD 操作失败 * Function descript:返回标志信息 ‘Error',和提示信息,当前系统繁忙,请稍后重试; */ function returnApiErrorExample(){ $result = array( 'flag' => 'Error', 'msg' => '当前系统繁忙,请稍后重试!', ); print json_encode($result); } /** * @param null $data * @return array|mixed|null * Function descript: 过滤post提交的参数; * */ function checkDataPost($data = null){ if(!empty($data)){ $data = explode(',',$data); foreach($data as $k=>$v){ if((!isset($_POST[$k]))||(empty($_POST[$k]))){ if($_POST[$k]!==0 && $_POST[$k]!=='0'){ returnApiError($k.'值为空!'); } } } unset($data); $data = I('post.'); unset($data['_URL_'],$data['token']); return $data; } } /** * @param null $data * @return array|mixed|null * Function descript: 过滤get提交的参数; * */ function checkDataGet($data = null){ if(!empty($data)){ $data = explode(',',$data); foreach($data as $k=>$v){ if((!isset($_GET[$k]))||(empty($_GET[$k]))){ if($_GET[$k]!==0 && $_GET[$k]!=='0'){ returnApiError($k.'值为空!'); } } } unset($data); $data = I('get.'); unset($data['_URL_'],$data['token']); return $data; } }

查询单个果品详细信息

/** * 发布模块 * * 获取信息单个果品详细信息 * */ public function getMyReleaseInfo(){ //检查是否通过post方法得到数据 checkdataPost('id'); $where['id'] = $_POST['id']; $field[] = 'id,fruit_name,high_price,low_price,address,size,weight,fruit_pic,remark'; $releaseInfo = $this->release_obj->findRelease($where,$field); $releaseInfo['remark'] = mb_substr($releaseInfo['remark'],0,49,'utf-8').'...'; //多张图地址按逗号截取字符串,截取后如果存在空数组则需要过滤掉 $releaseInfo['fruit_pic'] = array_filter(explode(',', $releaseInfo['fruit_pic'])); $fruit_pic = $releaseInfo['fruit_pic'];unset($releaseInfo['fruit_pic']); //为图片添加存储路径 foreach($fruit_pic as $k=>$v ){ $releaseInfo['fruit_pic'][] = 'http://'.$_SERVER['HTTP_HOST'].'/Uploads/Release/'.$v; } if($releaseInfo){ returnApiSuccess('',$releaseInfo); }else{ returnApiError( '什么也没查到(+_+)!'); } }

findRelease() 方法的model

/** * 查询一条数据 */ public function findRelease($where,$field){ if($where['status'] == '' || empty($where['status'])){ $where['status'] = array('neq','9'); } $result = $this->where($where)->field($field)->find(); return $result; }

app端接收到的数据(解码json之后)

{ "flag": "success", "message": "", "responseList": { "id": "2", "fruit_name": "苹果", "high_price": "8.0", "low_price": "5.0", "address": "天津小白楼水果市场", "size": "2.0", "weight": "2.0", "remark": "急需...", "fruit_pic": [ "http://fruit.txunda.com/Uploads/Release/201508/55599e7514815.png", "http://fruit.txunda.com/Uploads/Release/201508/554f2dc45b526.jpg" ] } }

app端接收到的数据(原生json串)

复制代码 代码如下:


{"flag":"success","message":"","responseList":{"id":"2","fruit_name":"\u82f9\u679c","high_price":"8.0","low_price":"5.0","address":"\u5929\u6d25\u5c0f\u767d\u697c\u6c34\u679c\u5e02\u573a","size":"2.0","weight":"2.0","remark":"\u6025\u9700...","fruit_pic":["http:\/\/fruit.txunda.com\/Uploads\/Release\/201508\/55599e7514815.png","http:\/\/fruit.txunda.com\/Uploads\/Release\/201508\/554f2dc45b526.jpg"]}}

方案二:另外我们还可以通过ThinkPHP实现移动端访问自动切换主题模板,这样也可以做到移动端访问

ThinkPHP的模板主题机制,,如果只是在PC,只要需修改 DEFAULT_THEME (新版模板主题默认是空,表示不启用模板主题功能)配置项就可以方便的实现多模板主题切换。

  但对于移动端和PC端,也许你会设计完全不同的主题风格,且针对不同的来路提供不同的渲染方式,其中一种比较流行的方法是“响应式设计”,但就本人经历而言,要实现完全的“响应式设计”并不是那么容易,且解决兼容问题也是个难题,假设是大型站点,比如:淘宝、百度、拍拍这些,响应式设计肯定是满足不了需求的,而是需要针对手机访问用户提供单独的手机网站。

ThinkPHP 完全可以实现,而且相当简单。和TPM的智能模版切换引擎一样,只要对来路进行判断处理即可。

一、将 ismobile() 加入到{项目/Common/common.php}

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles