Home Backend Development PHP Tutorial 使用Thinkphp框架开发移动端接口_php实例

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

Jun 07, 2016 pm 05:11 PM
php

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

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

<&#63;php
/**
 * Created by zhangkx
 * Email: zkx520tnhb@163.com
 * Date: 2015/8/1
 * Time: 23:15
 */
 
/*************************** api开发辅助函数 **********************/
 
/**
 * @param null $msg  返回正确的提示信息
 * @param flag success CURD 操作成功
 * @param array $data 具体返回信息
 * Function descript: 返回带参数,标志信息,提示信息的json 数组
 *
 */
function returnApiSuccess($msg = null,$data = array()){
  $result = array(
    'flag' => '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;
  }
}

Copy after login

查询单个果品详细信息

/**
  * 发布模块
  * 
  * 获取信息单个果品详细信息
  *
  */
  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( '什么也没查到(+_+)!');
    }
  }

Copy after login

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;
  }

Copy after login

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"
    ]
  }
}

Copy after login

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}

function ismobile() {
  // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
  if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    return true;
  
  //此条摘自TPM智能切换模板引擎,适合TPM开发
  if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
    return true;
  //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
  if (isset ($_SERVER['HTTP_VIA']))
    //找不到为flase,否则为true
    return stristr($_SERVER['HTTP_VIA'], 'wap') &#63; true : false;
  //判断手机发送的客户端标志,兼容性有待提高
  if (isset ($_SERVER['HTTP_USER_AGENT'])) {
    $clientkeywords = array(
      'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
    );
    //从HTTP_USER_AGENT中查找手机浏览器的关键字
    if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
      return true;
    }
  }
  //协议法,因为有可能不准确,放到最后判断
  if (isset ($_SERVER['HTTP_ACCEPT'])) {
    // 如果只支持wml并且不支持html那一定是移动设备
    // 如果支持wml和html但是wml在html之前则是移动设备
    if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
      return true;
    }
  }
  return false;
 }
Copy after login

二、在{项目/Lib/}创建一个 CommonAction.php,如果你的项目已公共控制器,则无需创建,直接加在里面即可。

Class CommonAction extends Action{
  Public function _initialize(){
    //移动设备浏览,则切换模板
    if (ismobile()) {
      //设置默认默认主题为 Mobile
      C('DEFAULT_THEME','Mobile');
    }
    //............你的更多代码.......
  }
 }
Copy after login

通过以上2种方式均可实现移动端访问,一种是原生,一种是伪原生,小伙伴们根据自己的项目需求来选择吧。

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles